1.includes()
在ES5中,我们常用indexOf()来判断某个字符串中是否包含另一个字符串,如下:
var str = 'hello world!'
var result = str.indexOf('lo') < 0 ? false : true
console.log(result) // true
这样我们需要加一层判断来得到我们需要的是否该字符串中存在某个字符串与否,ES6提供了更加简便的方法来达到这个效果
var str = 'hello world!'
var result = str.includes('uo')
console.log(result) // false
2.startsWith(),表示参数字符串是否在原字符串的头部
var str = 'hello world!'
var result = str.startsWith('hel')
console.log(result) // true
3.endsWith(),表示参数字符串是否在原字符串的尾部
var str = 'hello world!'
var result = str.endsWith('hel')
console.log(result) // false
4.字符串的遍历器接口,使得字符串可以被for...of循环遍历
var str = 'hell'
for(let item of str){
console.log(item) // 'h' 'e' 'l' 'l'
}
5.repeat(),返回一个新字符串,表示将原字符串重复n次
'xx'.repeat(2) // 'xxxx'
'hello'.repeat(3) // 'hellohellohello'
'li'.repeat(0) // ''
'li'.repeat(Infinity) // RangeError
'li'.repeat(-2) // RangeError
需要注意的是,repeat()的参数不能为负数或者Infinity,否则报错
6.padStart(),padEnd(),如果某个字符串不够制定长度,会在头部或尾部补全。padStart()用于头部补全,padEnd()用于尾部补全
console.log('aa'.padStart(5,'s')) // sssaa
console.log('aa'.padEnd(6,'g')) // aagggg