目录
1.Unicode支持
2.新增字符串API
3.正则中的粘连标记
4.模板字符串
1.Unicode支持
早期由于存储资源有限,Unicode使用16位二进制来存储文字,我们将一个16位二进制编码叫做一个码元(code unit)。
后来由于技术的发展,Unicode对文字编码进行了扩展,将某些文字扩展到了32位(占用了两个码元)【例1-1】,并且将某个文字对应的二进制数字叫做码点(code point)
ES6为了解决这一问题,为字符串提供了方法:codePointAt,根据字符串码元的位置得到其码点。同时,ES6为正则表达式添加了一个flag:u,添加该配置后,匹配时采用码点匹配
【例1-1】32位文字
const str = '桃花扇';console.log('桃花扇的码元长度为:',str.length);const text = '𠮷';console.log('𠮷的码元长度为:',text.length);
【结果】
【例1-2】码点
const text = '𠮷';console.log('𠮷的码元长度为:',text.length);console.log('𠮷的第一个码元:',text.charCodeAt(0).toString(16));console.log('𠮷的第二个码元:',text.charCodeAt(1).toString(16));console.log('𠮷的第一个码点:',text.codePointAt(0).toString(16));console.log('𠮷的第二个码点:',text.codePointAt(1).toString(16));
【结果】
【例1-3】求字符串的实际长度
const text = '𠮷';//判断该字符是否为32位二进制function is32bit(char, i) {//如果码点大于16位二进制的最大值,则其是32位的return char.codePointAt(i) > 0xffff;}//返回字符串的实际长度function getLengthOfCodePoint(str) {var len = 0;for (let i = 0; i < str.length; i++) {if (is32bit(str,i)) {//若第i格字符为32位,即占用了两个码元,则i++,跳过一个码元,len加一,进入下一次循环i ++;}len ++;}return len;}console.log('𠮷的长度位:',getLengthOfCodePoint(text));
【结果】
【例1-4】正则测试
const text = '𠮷';//下面正则表达式中,点表示任意字符,则正则表达式的含义为该字符开头,该字符结尾,即匹配单个字符const reg = /^.$/;console.log(reg.test(text));const reg1 = /^.$/u; //u码点匹配console.log(reg1.test(text));
【结果】
2.新增字符串API
(1)includes —— 判断字符串中是否包含指定的子字符串
(2)startsWith —— 判断字符串是否以指定字符串开始
(3)endsWith —— 判断字符串中是否以指定的字符串结尾
(4)repeat —— 将字符串重复指定的次数,然后返回一个新字符串
【例2】
const str = "jwh";console.log( '字符串str中是否含有w:',str.includes('w'));//第二位参数表示从(lastindex)第几个字符开始找起console.log('字符串str从第2个字符开始,后面是否含有j:',str.includes('j',1));console.log('字符串str是否以j开头:',str.startsWith('j'));console.log('字符串str是否以h结尾:',str.endsWith('h'));console.log(str.repeat(5))
【结果】
3.正则中的粘连标记
标记名:y
含义:匹配时,完全按照正则对象中lastIndex位置开始匹配,并且匹配的位置必须在lastIndex位置
【例3】
const str = 'Tao HuaShan'const reg = /H\w+/;console.log(reg.test(str));console.log(str.match(reg))const reg1 = /H\w+/y;console.log(reg1.test(str));reg1.lastIndex = 4;console.log(reg1.test(str));
【结果】
4.模板字符串
ES6之前处理字符串繁琐的两个方面:多行字符串,字符串拼接
在ES6中,提供了模板字符串的书写,可以非常方便的换行和拼接,规则是将字符串的引号改为反引号
如果要在字符串中拼接JS表达式,只需要在模板字符串中使用${JS表达式}
【例4】
const music1 = "If We Had Each Other";const music2 = "晴天"var favorite = `我最喜欢的英文歌是${music1}我最喜欢的中文歌是${music2}`console.log(favorite);
【结果】
这就很方便很奈斯