{
console.log('a',`\u0061`);//a a
console.log('s',`\u20BB7`);//口7 因为超过0xFFFF
console.log('s',`\u{20BB7}`);//��
}
//返回字符串长度,每两个字节一个长度
{
let r='a';
console.log('length',r.length);//1
let s='��'
console.log('length',s.length)//2
//es5
console.log('0',s.charAt(0));// 0, �
console.log('1',s.charAt(1));// 1, �
console.log('at0',s.charCodeAt(0));//at0, 65533
console.log('at1',s.charCodeAt(1));//at1, 65533
//es6
let s1='��a';//
console.log('length',s1.length);//3 获取字符长度
console.log('code0',s1.codePointAt(0));//65533 获取第1个字节的源码
console.log('code0',s1.codePointAt(0).toString(16));//fffd 获取第1个字节的16进制码
console.log('code1',s1.codePointAt(1));//65533 获取第2个字节的16进制码
console.log('code2',s1.codePointAt(2));//97 获取第3个字节的16进制码
}
//从码值变为字符
{
//es5方法
console.log(String.fromCharCode("0x20bb7"));//ஷ
//es6方法
console.log(String.fromCodePoint("0x20bb7"));//��
}
{
//es5方法
let str='\u{20bb7}abc';
for (let i=0;i<str.length;i++){
console.log('es5',str[i]);//�,�,a,b,c
}
//es6方法
for (let code of str){
console.log('es6',code);//��,a,b,c
}
}
{
//判断是否包含字符
let str='string';
console.log('includes',str.includes("s"));//true
console.log('includes',str.includes("f"));//false
//判断字符开始
console.log('str',str.startsWith("str"));//true
console.log('fff',str.startsWith("fff"));//false
//判断字符结束
console.log('str',str.endsWith("ing"));//true
console.log('ggg',str.endsWith("ggg"));//false
}
{
//复制拼接字符串
let str='abc';
console.log(str.repeat(2));//abcabc
}
//字符串套用
{
let name = 'makchikin';
let info = 'hello world';
let m =`I am ${name},${info}`;
console.log(m);//I am makchikin,hello world
}
//自动补白
{
console.log('1'.padStart(3,'0'));//001
console.log('1'.padEnd(4,'0'));//1000
}
//标签模板
{
let user={
name:'makchikin',
info:'hello workd'
};
console.log(abc `I am ${user.name},${user.info}!`);//I am ,,,!, makchikin, hello workd
function abc(s,v1,v2){
console.log(s,v1,v2);//I am ,,,!makchikinhello workd
return s+v1+v2;
}
}
//忽略转义字符
{
console.log(String.raw`hi\n${1+2}`);//hi\n3
console.log(`hi\n${1+2}`);//hi(换行了)
//3(换行了)
}
console