ES6 字符串扩展

Unicode 表示法

JavaScript 允许采用\uxxxx形式表示一个字符,其中xxxx表示字符的 Unicode 码点。

<script>
let a = "\u0061";
console.log(a);//a
</script>

字符串的遍历器接口

ES6为字符串添加了遍历器接口,语法 : let 变量名 of 字符串

<script>
for (let char of 'abc') {
  console.log(char);
}
// a b c
</script>

includes(), startsWith(), endsWith()

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

includes():返回布尔值,表示是否找到了参数字符串。

startsWith():返回布尔值,表示参数字符串是否在源字符串的头部。

endsWith():返回布尔值,表示参数字符串是否在源字符串的尾部。

var s = 'Hello world!';
s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true

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

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

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

repeat()

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

'hello'.repeat(2) // "hellohello"

模板字符串

ES6 支持模板变量语法 ${变量名称},可以方便地组合复杂的变量内容 :

<div id="demo"></div>
<script>
let name = "lesscode"
let html = `Hi, My name is ${name}`;
document.getElementById("demo").innerHTML = html;
</script>