ES6入门教程笔记(4)-字符串的扩展

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/foupwang/article/details/86586464

字符串的遍历器接口

ES6为字符串添加了遍历器接口,使字符串可以被for...of循环遍历。

for (let c of 'foo') {
    console.log(c);
}
// "f"
// "o"
// "o"

这个遍历器最大的优点是可以识别大于0xFFFF的Unicode码点,而传统的for循环无法识别这样的码点。

includes(),startsWith(),endsWith()

传统JavaScript只有indexOf方法,用来确定一个字符串是否包含在另一个字符串中。ES6又提供了三种新方法。

  • includes(): 返回布尔值,表示是否找到了参数字符串。
  • startsWith(): 返回布尔值,表示参数字符串是否在原字符串的头部。
  • endsWith(): 返回布尔值,表示参数字符串是否在原字符串的尾部。
let s = 'Hello world!';

s.includes('w') // true
s.startsWith('Hello') // true
s.endsWith('!') // true

这三个方法都支持第2个参数,表示开始搜索的位置。

let s = 'Hello world!';

s.includes('Hello', 6) // false
s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true

上面代码中,使用第2个参数n时,endsWith的行为与其他两个方法不同,它针对前n个字符,而其它两个方法针对从第n个位置直到字符串结束。

repeat()

repeat方法将原字符串重复n次,然后返回一个新字符串。

'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"

注:本文原始内容来自 ES6标准入门,有修改。

猜你喜欢

转载自blog.csdn.net/foupwang/article/details/86586464