以下整理 ES6(JavaScript 6)中字串的四個新用法:
一、Unicode 字元的新表示法
Unicode 字元通常是 21 個 bit,而一般 JavaScript 字元(大部分)是 16 bit,可以編碼成 UTF-16。超過 16 bit 的字元則需要用兩個一般字元來表示。
例如,下面的程式碼會輸出一個 Unicode 小火箭字元('\uD83D\uDE80'),你可以在瀏覽器的 console 裡試試:
console.log('\uD83D\uDE80');
在 ES6 裡,我們可以用更簡潔的新寫法:
console.log('\u{1F680}');
二、多行字串與模板字串
模板字串提供了三項實用的語法功能。
首先,模板字串支援嵌入變數:
let first = 'Jane'; let last = 'Doe'; console.log(`Hello ${first} ${last}!`); // Hello Jane Doe!
其次,模板字串可以直接定義多行字串:
let multiLine = ` This is a string with multiple lines`;
第三,如果你在字串前加上 String.raw 前綴,字串就會保持原始狀態。反斜線(\)不再代表跳脫,像 \n 這類特殊字元也不會被轉義:
let raw = String.raw`Not a newline: \n`; console.log(raw === 'Not a newline: \\n'); // true
三、遍歷字串
字串是可以遍歷的,你可以用 for-of 迴圈逐一取出字串中的每個字元:
for (let ch of 'abc') { console.log(ch); } // 輸出: // a // b // c
此外,你還能用展開運算子(...)把字串拆成字元陣列:
let chars = [...'abc']; // ['a', 'b', 'c']
四、字串包含判斷與重複
ES6 新增了三個方法,用來檢查一個字串是否包含另一個字串:
> '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
repeat() 方法則能重複產生字串:
> 'doo '.repeat(3) 'doo doo doo '
總結
以上就是 ES6 中字串的四個新用法,希望對大家有所幫助,若有疑問歡迎留言交流。