ES6——字符串扩展

来源:互联网 发布:wind软件 编辑:程序博客网 时间:2024/05/22 02:11

字符串新增方法


includes——是否包含

let str = 'string';console.log(str.includes('r'));  // true


startsWith——是否以xxx开头

let str = 'string';console.log(str.startsWith('str')); // true


endsWith——是否以xxx结尾

let str = 'string';console.log(str.endsWith('str')); // true


repeat——重复

let str = 'happy';console.log(str.repeat(2)); // happyhappy


String.raw——不换行

console.log(String.raw`Hi\n World`));  // Hi\n World

其实就是不识别换行符


模版字符串


使用$符号,把变量插入到字符串。

let name = 'Tim Chen' ;let info = 'cool man' ;let me = `I am ${name} and I'm a ${info}` ;console.log(me); // I am Tim Chen and I'm a cool man



Unicode相关


unicode表示法

当unicode字符大于2个字节的时候,我们可以使用花括号包起来。

console.log('two',`\u{20bb7}`);



codePoint(取unicode码值)


es5中,可以使用charCodeAt去匹配到字符的unicode码值。

但是如果该字符,超过2个字节,变成了4个字节,charCodeAt的值就会有2个。charCodeAt(0)和charCodeAt(1)。


而在es6中,利用codePointAt去匹配字符,哪怕该字符是4个字节的,

charCodeAt(0)依旧会把该字符完整的unicode码值(1-4字节)匹配到,

而此时charCodeAt(1)依旧会匹配到该字符的3、4字节。



fromCodePoint方法(取字符)


es5中有fromCharCode

它们之间的不同在于是否能识别大于2个字节的字符。



let of遍历器

let str = '\u{20bb7}abc';es5for(var i = 0; i < str.length; i++){    console.log('es5',str[i]);}es6使用遍历器for(let code of str){    console.log('es6',code);}

es5的方法,虽然也能遍历,但是由于该字符大于2个字节,所以有乱码。

es6使用遍历器,则能正确识别出来。


es2017方法


使用以下方法,需要安装babel-polyfill


padStart——向前补全


语法

字符串.padStart(长度,'补全用字符')


实例

console.log('1'.padStart(2,'0'));   // 01



padEnd——向后补全


实例

console.log('1'.padEnd(2,'0'));   // 10
原创粉丝点击