学习ES6:字符串扩展

参考 阮一峰 《ES6 标准入门》

模版字符串

使用反引号`标识, 模版字符串可以填充普通字符串,也可以定义多行字符串。

  • 使用多行模版时,所有的空格缩进都会被保存在输出中。
  • 使用${}嵌入变量,{}中可以写任何js表达式。
  • 模版中使用反引号用反斜杠\转义。

字符串遍历器

为字符串添加了Iterator,使之可以通过for..of...遍历。

1
2
3
4
5
6
7
8
9
for (let letter of 'string') {
console.log(letter);
}
//"s"
//"t"
//"r"
//"i"
//"n"
//"g"

字符串扩展API

只记录我感觉常用或比较实用的部分。

includes()

includes(str[, postion])
Function: 字符串中是否存在参数字符串
return: boolean

1
2
3
4
5
let string = 'javascript';

console.log(string.includes('av')); //true
console.log(string.includes('av', 1)); //true
console.log(string.includes('av', 3)); //false

startsWith()

startsWith(str[, postion])
Function: 字符串是否以参数字符串开头
return: boolean

1
2
3
4
5
let string = 'javascript';

console.log(string.startsWith('ja')); //true
console.log(string.startsWith('av', 1)); //true
console.log(string.startsWith('ja', 1)); //false

endsWith()

endsWith(str[, postion])
Function: 字符串是否以参数字符串结尾
return: boolean

1
2
3
4
5
let string = 'javascript';

console.log(string.endsWith('pt')); //true
console.log(string.endsWith('pt', 1)); //false
console.log(string.endsWith('av', 3)); //true

repeat()

repeat(count)
Function: 将字符串重复count次 count非整数会被向下取整,非数字会先转成数字
return: string

1
2
3
4
5
6
console.log('x'.repeat(3)); //'xxx'
console.log('x'.repeat(3.2)); //'xxx'
console.log('x'.repeat(3.6)); //'xxx'
console.log('x'.repeat(0)); //''
console.log('x'.repeat('3')); //'xxx'
console.log('x'.repeat('a')); //''