文章目录
ES6 之前判断字符串是否包含子串,用 indexOf 方法,ES6 新增了子串的识别方法
字符串的新增方法
1.includes() 是否找到参数字符串
let str='abc';
console.log(str.includes('a')); //true
2.监测子串是否在字符串的头部或尾部
let str='abac';
console.log(str.startsWith('a')); //true
console.log(str.startsWith('a', 2)); //true
console.log(str.endsWith('c')); //true
console.log(str.endsWith('c',0)); //false
3.repeat() 将字符串重复n次
let str='abc';
console.log(str.repeat(3)); //abcabcabc
如果参数是小数,向下取整
console.log(str.repeat(2.6)); //abcabc
如果参数是-1~0 , 0~1,或NaN,重复0次
4.补全字符串 padStart padEnd
第一个参数是指定生成的字符串的最小长度(补全后的总长度),第二个参数是用来补全的字符串。
如果没有指定第二个参数,默认用空格填充
console.log("h".padStart(5,"o")); // "ooooh"
console.log("h".padEnd(5,"o")); // "hoooo"
console.log("h".padStart(5)); // " h"
如果指定的长度小于或者等于原字符串的长度,则返回原字符串
console.log("hello".padStart(5,"A")); // "hello"
如果原字符串加上补全字符串长度大于指定长度,则截去超出位数的补全字符串
console.log("hello".padEnd(10,",world!")); // "hello,worl"
5.模板字符串 ``
es5字符串拼接:+
es6: ${变量}
(1)普通字符串
let w=`world!`
let s=`hello ${w}`;
console.log(s); //hello world!
(2)多行字符串
es5中多行拼接会报错,模板字符串可以解决这个问题
但是回车 空格会被保留
let str=`
Hey,
<span>${w}</span>
`
console.log(str);
(3)字符串可以插入变量和表达式
let name = "Mike";
let age = 27;
let info = `My Name is ${name},I am ${age+1} years old next year.`
console.log(info);
// My Name is Mike,I am 28 years old next year
(4)字符串中可以调用函数
function f(){
return "have fun!";
}
let string2= `Game start,${f()}`;
console.log(string2); // Game start,have fun!
6.trim()一致的方法 trimStart trimeEnd
trim() 头部去空
trimStart() 头部去空
trimeEnd() 尾部去空
7.replaceAll()
以前需要使用replace+全局正则g
let str="abcabcabc"
console.log(str.replaceAll('a', 1)); //1bc1bc1bc