ES6 新增了很多方法如:includes(),startsWith(),endsWith(),repeat(),padStart(),padEnd(),trimStart(),trimEnd(),at()
includes():返回布尔值,判断是否找到参数字符串
let string = "hello,words,hi";
console.log(string.includes("hello")); // true
startsWith():返回布尔值,判断参数字符串是否在原字符串的头部
let string = "hello,words,hi";
console.log(string.startsWith("hello")); // true
endsWith():返回布尔值,判断参数字符串是否在原字符串的尾部
let string = "hello,words,hi";
console.log(string.endsWith("hello")); // false
console.log(string.endsWith("hi")); // true
repeat():返回新的字符串,表示将字符串重复指定次数返回
console.log("hello,".repeat(3));//"hello,hello,hello"
如果参数是小数,向下取整
console.log("hello,".repeat(3.3));//"hello,hello,hello"
如果参数是 0 至 -1 之间的小数或者NaN,会进行取整运算,等同于 repeat 零次
console.log("hello,".repeat((-0.1)); console.log("hello,".repeat((NaN));
如果参数是负数或者 Infinity ,会报错:
console.log("hello,".repeat((-1)); // RangeError: Invalid count value
console.log("hello,".repeat((Infinity )); // RangeError: Invalid count value
padStart():返回新的字符串,表示用参数字符串从头部(左侧)补全原字符串
console.log("a".padStart(3,"b"));//"bba"
3是表示返回的字符串长度
padEnd():返回新的字符串,表示用参数字符串从尾部(右侧)补全原字符串
console.log("a".padEnd(3,"b"));//"abb"
如果指定的长度小于或者等于原字符串的长度,则返回原字符串:
console.log("hi".padStart(2,"b"));//"hi"
如果原字符串加上补全字符串长度大于指定长度,则截去超出位数的补全字符串:
console.log("hi".padEnd(6,",hhha"));//"hi,hhh"
常用于补全位数
trim():消除字符串空格
trimStart(): 消除字符串头部的空格
trimEnd(): 消除字符串尾部的空格
console.log(' hello'.trimStart());//hello
console.log(' hello '.trim());//hello
console.log('hello '.trimEnd());//hello
at():返回参数指定位置的字符,支持负索引
console.log('hello'.at(1));//e
console.log('hello'.at(-1));//o
console.log('hello'.at(10));//undefined