
上QQ阅读APP看书,第一时间看更新
1.3 字符串扩展
1.3.1 Unicode支持
Unicode的目标是为世界上每一个字符提供唯一标识符,唯一标识符称为码位或码点(Code Point)。而这些码位是用于表示字符的,又称为字符编码(Character Encode)。JavaScript里是可以通过\uxxxx的形式来表示一个字符,例如:\u0061表示字符a。但是这种语法限于码点在U+0000~U+FFFF之间的字符。超出这个范围的字符必须用两个字节来表示,例如:

ES6针对上述情况增加了大括号来让字符正确解读,代码如下:

1.3.2 新增字符串方法
在ES5中,一般通过indexOf方法来判断一个字符串是否包含在另外一个字符串中。如果能够找到就会返回被查找字符串的索引位置,如果没有找到就会返还“-1”,如:

ES6中新增了includes()、startsWith()、endsWith()方法来查找字符串。
includes():返还布尔值,表示是否找到了字符串。
startsWith():返还布尔值,表示被检测字符串是否在源字符串的头部。
endsWith():返还布尔值,表示被检测字符串是否在源字符串的结尾。

ES6标准中也新增了repeat()方法返回新的字符串将源字符串循环指定次数。例如:

1.3.3 模板字符串
ES5标准中一般输出模板是通过字符串拼接的方式来进行的,例如:

在上述字符串拼接中注意单双引号的使用。如果遇到多行字符串的情况需要通过“\n”来手动换行。但是在ES6中可以通过模板字符串简化上述写法,模板字符串通过反引号来表示“``”。如果要嵌入变量通过“${}”来实现:


模板字符串在使用过程中支持多行字符串,“${}”里可以接收三目运算符。遇到特殊字符同样需要通过“\”来进行转义:
