es6 语法 (字符串扩展)

Posted 小角色Byme

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了es6 语法 (字符串扩展)相关的知识,希望对你有一定的参考价值。

{
console.log(‘a‘,`\u0061`); //a,a
console.log(‘s‘,`\u20BB7`); //s ?7
console.log(‘s‘,`\u{20BB7}`) //s ??

}
//charCodeAt 和 codePointAt
{
let s = ‘a‘;
let a = ‘??‘;
console.log(‘length‘,s.length,a.length); //1,2
console.log(‘0‘,a.charAt(0)); //取字符 0 ?
console.log(‘1‘,a.charAt(1)); //取字符 1 ?
console.log(‘0‘,a.charCodeAt(0)); //取编码 0 55362
console.log(‘0‘,a.charCodeAt(1)); //取编码 0 57271

let s1 = ‘??a‘;
console.log(‘length‘,s1.length); //length 3 ??占俩字符
console.log(‘code0‘,s1.codePointAt(0)); //code0 134071 为十进制
console.log(‘code0‘,s1.codePointAt(0).toString(16)); //code0 20bb7 为十六进制
console.log(‘code1‘,s1.codePointAt(1)); //code1 57271
console.log(‘code2‘,s1.codePointAt(2)); //code2 97 其实就是a
}
//fromCharCode 和 fromCodePoint
{
console.log(String.fromCharCode(‘0x20bb7‘)); //?
console.log(String.fromCodePoint(‘0x20bb7‘));//??
}
//code 处理遍历编码
{
let str = ‘\u{20bb7}abc‘;
for(let i=0;i<str.length;i++){
console.log(‘es5‘,str[i]); //? ? a b c
}

for(let code of str){
console.log(‘es6‘,code); //?? a b c
}

}


//includes startsWith endsWith 包含,开始,结束某字符串
{
let str = ‘string‘;
console.log(‘include‘,str.includes(‘c‘)); //include false
console.log(‘start‘,str.startsWith(‘str‘)); //start true
console.log(‘end‘,str.endsWith(‘ng‘)); //start true
}
//复制
{
let str = ‘abc‘;
console.log(str.repeat(2)); //abcabc
}
//模板字符串
{
let name = ‘list‘;
let info = ‘hell world‘;
let m = `i am ${name},${info}`;
console.log(m); //i am list,hell world
}
//补白 padStart padEnd 1不够两位,给它补一个0.
{
console.log(‘1‘.padStart(2,‘0‘)); //01
console.log(‘1‘.padEnd(2,‘0‘)); //10
}
//标签模板
{
let user = {
name:‘list‘,
info:‘hello world‘
};
abc`i am ${user.name},${user.info}`;
function abc(s,v1,v2){
console.log(s,v1,v2); // "i am ", ",", ""
}
}
{
let user = {
name:‘list‘,
info:‘hello world‘
};
console.log(‘111‘,abc`i am ${user.name},${user.info}`); // 111 i am ,,,listhello world
function abc(s,v1,v2){
console.log(‘222‘,s,v1,v2); // 222 "i am ", ",", ""
return s+v1+v2;
}
}

//raw 转义
{
console.log(String.raw`Hi\n${1+2}`); // Hi\n3
console.log(`Hi\n${1+2}`); // Hi 3
}

以上是关于es6 语法 (字符串扩展)的主要内容,如果未能解决你的问题,请参考以下文章

ES6语法——字符串扩展

ES6新语法之---对象字面量扩展模板字符串

es6 语法 (字符串扩展)

vue常用的ES6语法--内置对象扩展

ES6新增语法详述 𳞰

ES6新增语法详述 𠀶