字符的Unicode表示法
\uxxxx可以表示一个双字节的字符(xxxx表示字符编码,范围在0000---FFFF),超出此范围用两个双字节表示。
console.log("\u0061"); //aconsole.log("\uD842\uDFB7") //?
使用大括号可以正确识别双字符及超出的字符:
console.log("\u0041"); //Aconsole.log("\u{41}") //Aconsole.log("\u{20BB7}") //?
codePointAt(codePointAt总是返回10进制值,要想返回16进制用toString。可以正确的识别码点大于FFFF的字符)
var s = "?a";console.log(s.length) //3 码点大于FFFF的字符总是占两个位置console.log(s.charAt(0)); //"" charAt返回当前位置的字符console.log(s.charAt(1)); //""console.log(s.charAt(2)); //aconsole.log(s.charCodeAt(0).toString(16)); //d842 charCodeAt返回当前位置字符对应的码点,不能识别码点大于FFFF的字符console.log(s.charCodeAt(1).toString(16)); //dfb7console.log(s.charCodeAt(2).toString(16)); //61console.log(s.codePointAt(0).toString(16)); //20bb7 codePointAt返回当前位置字符对应的码点,能识别码点大于FFFF的字符console.log(s.codePointAt(1).toString(16)); //dfb7 对于码点在0000---FFFF的字符,与charCodeAt返回结果相同console.log(s.codePointAt(2).toString(16)); //61
String.fromCodePoint()(用于从码点返回对应字符)
String.fromCharCode(61) // =String.fromCharCode(0x20BB7) //ஷ fromCharCode只能识别码点在0000———FFFF范围内String.fromCodePoint(61) // =String.fromCodePoint(0x20BB7) //? fromCodePoint都能识别
字符串的遍历接口for...of
for (let str of "abc") { console.log(str)}// a b c
at()(返回当前位置的字符)
'abc'.charAt(0) // "a"'?'.charAt(0) // "\uD842"'abc'.at(0) // "a"'?'.at(0) // "?"
normalize()(将字符的不同表示方法统一为同样的形式)
'\u01D1'==='\u004F\u030C' //false'\u01D1'.normalize() === '\u004F\u030C'.normalize() // true
includes(), startsWith(), endsWith()
- includes()(返回布尔值,表示是否找到了参数字符串)
- startsWith()(返回布尔值,表示参数字符串是否在原字符串的头部)
- endsWith()(返回布尔值,表示参数字符串是否在原字符串的尾部)
let s = "hello world";s.includes("ll"); //trues.startsWith("he"); //trues.endsWith("ld"); //true
repeat()(先取整,后重复)
"x".repeat(3) //xxx"x".repeat(2.9) //xxx"x".repeat(Infinity) //RangeError"x".repeat(-1) //RangeError"x".repeat(-0.9) //"x""x".repeat(NaN) //"x"
padStart(),padEnd()(字符串补全,padStart()
用于头部补全,padEnd()
用于尾部补全。接受两个参数,第一个参数用来指定字符串的最小长度,第二个参数是用来补全的字符串。)
'12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"'x'.padEnd(4, 'ab') // 'xaba''xxx'.padStart(2, 'ab') // 'xxx' 原字符串的长度,等于或大于指定的最小长度,则返回原字符串。'abc'.padStart(10, '0123456789') // '0123456abc' 用来补全的字符串与原字符串,两者的长度之和超过了指定的最小长度,则会截去超出位数的补全字符串。'x'.padStart(4) // ' x' 省略第二个参数,默认使用空格补全长度。
模板字符串(用“ ` ` ”来表示模板字符串,用${}插入变量)
var a = "everyone";var b = `hello ${a}`;var c = `hello ${'everyone'}` //大括号内部是一个字符串,将会原样输出console.log(b) //hello everyoneconsole.log(c) //hello everyone
模板编译(<%...%>)
let template = `
- <% for(let i=0; i < data.supplies.length; i++) { %>
- <%= data.supplies[i] %> <% } %>
标签模板(模板字符串紧跟在一个函数名后面,该函数将被调用来处理这个模板字符串)
alert`123`// 等同于alert(123)
String.raw()(用来充当模板字符串的处理函数,返回一个斜杠都被转义(即斜杠前面再加一个斜杠)的字符串)
String.raw`Hi\n${2+3}!`;// "Hi\\n5!"