ES6字符串相关

202 阅读2分钟

1.字符的Unicode表示法

(1)只要将码点放入大括号,就能正确解读该字符。

"\u{20BB7}"
// "𠮷"

"\u{41}\u{42}\u{43}"
// "ABC"

let hello = 123;
hell\u{6F} // 123

'\u{1F680}' === '\uD83D\uDE80'
// true

2.字符串的遍历器接口

(1)ES6 为字符串添加了遍历器接口(详见《Iterator》一章),使得字符串可以被for...of循环遍历。

for (let codePoint of 'foo') {
  console.log(codePoint)
}
// "f"
// "o"
// "o"

let text = String.fromCodePoint(0x20BB7);

for (let i = 0; i < text.length; i++) {
  console.log(text[i]);
}
// " "
// " "

for (let i of text) {
  console.log(i);
}
// "𠮷"

上面代码中,字符串text只有一个字符,但是for循环会认为它包含两个字符(都不可打印),而for...of循环会正确识别出这一个字符。

3.模板字符串

(1)用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。

(2)如果使用模板字符串表示多行字符串,所有的空格和缩进都会被保留在输出之中。

4.字符串的新增方法

(1)String.fromCodePoint():用于从 Unicode 码点返回对应字符

(2)includes(), startsWith(), endsWith()

   1.includes():返回布尔值,表示是否找到了参数字符串。

_  2.startsWith():返回布尔值,表示参数字符串是否在原字符串的头部。_

_  3.endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。_

let s = 'Hello world!';

s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false

上面代码表示,使用第二个参数n时,endsWith的行为与其他两个方法有所不同。它针对前**n**个字符,而其他两个方法针对从第n个位置直到字符串结束。

(3)repeat():返回一个新字符串,表示将原字符串重复n次。参数如果是小数,会被取整。

'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""
'na'.repeat(2.9) // "nana"

(4)padStart(),padEnd() :字符串补全长度的功能。如果某个字符串不够指定长度,会在头部或尾部补全。padStart()用于头部补全,padEnd()用于尾部补全。如果省略第二个参数,默认使用空格补全长度。

'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'

'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'

另一个用途是提示字符串格式。

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

(5)trim(), trimStart(),trimEnd() :分别为消除两端空格。头部,尾部

const s = '  abc  ';

s.trim() // "abc"
s.trimStart() // "abc  "
s.trimEnd() // "  abc"

(6)matchAll():返回一个正则表达式在当前字符串的所有匹配