ES6-----学习系列四(字符串扩展)
一、字符串的扩展主要是新增了一些特性
1、Unicode码
{ console.log('a',`\u0061`); console.log('s',`\u20BB7`);//无法正常输出 console.log('s',`\u{20BB7}`);//输出 𠮷 这个字符 }
{ let s='𠮷'; console.log('length',s.length);//2 console.log('0',s.charAt(0));//乱码 console.log('1',s.charAt(1));//乱码 console.log('at0',s.charCodeAt(0)); console.log('at1',s.charCodeAt(1)); let s1='𠮷a'; console.log('length',s1.length); console.log('code0',s1.codePointAt(0));// console.log('code0',s1.codePointAt(0).toString(16));//20bb7 console.log('code1',s1.codePointAt(1));//𠮷的最后两个字节
console.log('code2',s1.codePointAt(2));//97(也就是a) }
{ console.log(String.fromCharCode("0x20bb7")); console.log(String.fromCodePoint("0x20bb7")); }
{ let str='\u{20bb7}abc'; for(let i=0;i<str.length;i++){ console.log('es5',str[i]); } for(let code of str){ console.log('es6',code);//for of可以遍历大于0xfff的字符
} }
2、api
①、includes startsWith endsWith
{ let str="string"; console.log('includes',str.includes("c"));//判断字符串是否包含给定字符(includes) console.log('start',str.startsWith('str'));//判断是否以给定字符开始(startsWith) console.log('end',str.endsWith('ng'));//判断是否以给定字符结束(endsWith) }
②、repeat
{ let str="abc"; console.log(str.repeat(2));//abcabc }
③、padStart padEnd(补全)
{ console.log('1'.padStart(2,'0'));//01 console.log('1'.padEnd(2,'0'));//10 }
④、raw(进行转义)
{ console.log(String.raw`Hi\n${1+2}`); Hi 3(不换行) console.log(`Hi\n${1+2}`);Hi 3(换行) }
3、字符串模板(感觉挺重要的,注意不是单引号,是键盘里面数字1左侧的按键,同时引用变量要用${})
{ let name="list"; let info="hello world"; let m=`i am ${name},${info}`; console.log(m); }
4、标签模板
{ let user={ name:'list', info:'hello world' }; console.log(abc`i am ${user.name},${user.info}`); function abc(s,v1,v2){ console.log(s,v1,v2); return s+v1+v2 } }