codePointAt()
JavaScript-16 的格式储存,每个字符固定为两个字节。需要四个字节储存的字符,JavaScript 会认为那是两个字符。
ES6 提供了 codePointAt 方法,能够正确处理四个字节储存的字符,返回一个字符的码点。
String.fromCodePoint()
识别 UTF-32 字符。
includes()、startsWith()、endsWith()
1 2 3 4 5 6 7
| var s = "hello world" s.startWith("hello") s.endsWith("d") s.includes("o")
s.startsWith("world", 6) s.includes("hello", 6)
|
repeat()
1 2 3 4 5 6 7 8 9 10 11
| "x".repeat(3) "na".repeat(0)
"na".repeat(2.9)
"na".repeat(Infinity) "na".repeat(-1)
"na".repeat(-0.9) "na".repeat(NaN) "na".repeat("3")
|
padStart(), padEnd()
首、尾补全
1 2 3 4 5 6 7 8 9
| "x".padStart(5, "ab") "x".padStart(4, "ab") "x".padEnd(5, "ab")
"x".padStart(5) "x".padEnd(5)
"1".padStart(10, "0") "09-12".padStart(10, "YYYY-MM-DD")
|
模板字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| let name = "test" ;`name : ${name}`
let x = 1, y = 2 ;`${x} + ${y} = ${x + y}`
let obj = { x: 1, y: 2 } ;`{obj.x + obj.y}`
function fn() { return "test" } ;`foo $(fn)`
|
String.raw()
String.raw 方法用来充当模板字符串的处理函数,返回一个斜线都被转义的字符串,对应于替换变量后的模板字符串。
1 2
| String.raw(`Hi\n${1 + 3}`)
|