Unicode字符的新表示方法
Unicode字符通常是21个bit的,而普通的JavaScript字符(大部分)是16bit的,可以编码成UTF-16。超过16bit的字符需要用2个常规字符表示。比如,比如下面的的代码将会输出一个Unicode小火箭字符(‘\uD83D\uDE80’),你可以在浏览器的console里试一下:
console.log('\uD83D\uDE80');
在 ECMAScript 6 里,可以使用新的表示方法,更简洁:
console.log('\u{1F680}');
多行字符串定义和模板字符串
模板字符串提供了三个有用的语法功能。
首先,模板字符串支持嵌入字符串变量:
1 let first = 'Jane'; 2 let last = 'Doe'; 3 console.log(`Hello ${first} ${last}!`); 4 // Hello Jane Doe!
第二,模板字符串支持直接定义多行字符串:
1 let multiLine = ` 2 This is 3 a string 4 with multiple 5 lines`;
第三,如果你把字符串加上String.raw前缀,字符串将会保持原始状况。反斜线(\)将不表示转义,其它专业字符,比如 \n 也不会被转义:
1let raw = String.raw`Not a newline: \n`; 2 console.log(raw === 'Not a newline: \\n'); // true
循环遍历字符串
字符串可遍历循环,你可以使用 for-of 循环字符串里的每个字符:
1 for (let ch of 'abc') { 2 console.log(ch); 3 } 4 // Output: 5 // a 6 // b 7 // c
而且,你可以使用拆分符 (...) 将字符串拆分成字符数组:
1 let chars = [...'abc']; 2 // ['a', 'b', 'c']
字符串包含判断和重复复制字符串
有三个新的方法能检查一个字符串是否包含另外一个字符串:
1> 'hello'.startsWith('hell') 2true 3> 'hello'.endsWith('ello') 4true 5> 'hello'.includes('ell') 6true
这些方法有一个可选的第二个参数,指出搜索的起始位置:
1> 'hello'.startsWith('ello', 1) 2true 3> 'hello'.endsWith('hell', 4) 4true 5 6> 'hello'.includes('ell', 1) 7true 8> 'hello'.includes('ell', 2) 9false
repeat()方法能重复复制字符串:
1> 'doo '.repeat(3) 2 'doo doo doo '
