字符串的扩展

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") //true
s.endsWith("d") //true
s.includes("o") //true

s.startsWith("world", 6) //true;
s.includes("hello", 6) //false

repeat()

1
2
3
4
5
6
7
8
9
10
11
"x".repeat(3) //'xxx'
"na".repeat(0) //''

"na".repeat(2.9) //取整 -> 'nana'

"na".repeat(Infinity) //Error
"na".repeat(-1) //Error

"na".repeat(-0.9) //''
"na".repeat(NaN) //''
"na".repeat("3") //'nanana'

padStart(), padEnd()

首、尾补全

1
2
3
4
5
6
7
8
9
"x".padStart(5, "ab") //'ababx'
"x".padStart(4, "ab") //'abax'
"x".padEnd(5, "ab") //'xabab'

"x".padStart(5) //' x'
"x".padEnd(5) //'x '

"1".padStart(10, "0") //'0000000001'
"09-12".padStart(10, "YYYY-MM-DD") //'YYYY-09-12'

模板字符串

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}`
//1 + 2 = 3

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}`)
//Hi\\n4