6. 新的字串功能
目錄
請支持這本書:購買它(PDF、EPUB、MOBI)捐款
(廣告,請不要封鎖。)

6. 新的字串功能



6.1 概述

新的字串方法

> 'hello'.startsWith('hell')
true
> 'hello'.endsWith('ello')
true
> 'hello'.includes('ell')
true
> 'doo '.repeat(3)
'doo doo doo '

ES6 有一種新的字串字面值,稱為範本字面值

// String interpolation via template literals (in backticks)
const first = 'Jane';
const last = 'Doe';
console.log(`Hello ${first} ${last}!`);
    // Hello Jane Doe!

// Template literals also let you create strings with multiple lines
const multiLine = `
This is
a string
with multiple
lines`;

6.2 Unicode 碼點跳脫

在 ECMAScript 6 中,有一種新的 Unicode 跳脫,讓您可以指定任何碼點(甚至超過 16 位元)

console.log('\u{1F680}');    // ES6: single code point
console.log('\uD83D\uDE80'); // ES5: two code units

有關跳脫的更多資訊,請參閱Unicode 章節

6.3 字串插值、多行字串字面值和原始字串字面值

範本字面值在其專屬章節中有深入的說明。它們提供了三個有趣的特色。

首先,範本字面值支援字串插值

const first = 'Jane';
const last = 'Doe';
console.log(`Hello ${first} ${last}!`);
    // Hello Jane Doe!

其次,範本字面值可以包含多行

const multiLine = `
This is
a string
with multiple
lines`;

第三,如果您在範本字面值前面加上標籤String.raw,它們就是「原始」的,反斜線不是特殊字元,而且不會解釋跳脫,例如 \n

const str = String.raw`Not a newline: \n`;
console.log(str === 'Not a newline: \\n'); // true

6.4 迭代字串

字串是可迭代的,這表示您可以使用 for-of 來迭代它們的字元

for (const ch of 'abc') {
    console.log(ch);
}
// Output:
// a
// b
// c

而且您可以使用展開運算子 (...) 將字串轉換成陣列

const chars = [...'abc'];
    // ['a', 'b', 'c']

6.4.1 迭代遵循 Unicode 碼點

字串迭代器會沿著碼點邊界分割字串,這表示它傳回的字串包含一個或兩個 JavaScript 字元

for (const ch of 'x\uD83D\uDE80y') {
    console.log(ch.length);
}
// Output:
// 1
// 2
// 1

6.4.2 計算碼點

反覆運算提供一種快速的方式來計算字串中的 Unicode 碼點

> [...'x\uD83D\uDE80y'].length
3

6.4.3 反轉包含非 BMP 碼點的字串

反覆運算也有助於反轉包含非 BMP 碼點(大於 16 位元,並編碼為兩個 JavaScript 字元)的字串

const str = 'x\uD83D\uDE80y';

// ES5: \uD83D\uDE80 are (incorrectly) reversed
console.log(str.split('').reverse().join(''));
    // 'y\uDE80\uD83Dx'

// ES6: order of \uD83D\uDE80 is preserved
console.log([...str].reverse().join(''));
    // 'y\uD83D\uDE80x'
The two reversed strings in the Firefox console.
Firefox 主控台中反轉的兩個字串。

6.5 碼點的數值

新的方法 codePointAt() 傳回字串中特定索引處碼點的數值

const str = 'x\uD83D\uDE80y';
console.log(str.codePointAt(0).toString(16)); // 78
console.log(str.codePointAt(1).toString(16)); // 1f680
console.log(str.codePointAt(3).toString(16)); // 79

此方法與字串反覆運算結合使用時效果良好

for (const ch of 'x\uD83D\uDE80y') {
    console.log(ch.codePointAt(0).toString(16));
}
// Output:
// 78
// 1f680
// 79

codePointAt() 的相反方法是 String.fromCodePoint()

> String.fromCodePoint(0x78, 0x1f680, 0x79) === 'x\uD83D\uDE80y'
true

6.6 檢查是否包含

三個新方法檢查一個字串是否存在於另一個字串中

> 'hello'.startsWith('hell')
true
> 'hello'.endsWith('ello')
true
> 'hello'.includes('ell')
true

這些方法中的每一個都有一個位置作為可選的第二個參數,指定要搜尋的字串從何處開始或結束

> 'hello'.startsWith('ello', 1)
true
> 'hello'.endsWith('hell', 4)
true

> 'hello'.includes('ell', 1)
true
> 'hello'.includes('ell', 2)
false

6.7 重複字串

repeat() 方法重複字串

> 'doo '.repeat(3)
'doo doo doo '

6.8 將正規表示式工作委派給參數的字串方法

在 ES6 中,接受正規表示式參數的四個字串方法所做的工作相對較少。它們主要呼叫參數的方法

參數不再必須是正規表示式。任何具有適當方法的物件都可以。

6.9 參考:新的字串方法

標記範本

Unicode 和碼點

尋找字串

重複字串

下一頁:7. 符號