三、字符串的擴展
1. 字符的Unicode表示法
ES6加強了對Unicode的支持:
(1)運行 \uxxxx表示一個字符,其中xxxx表示字符的Unicode碼點
(2)ES6改進。將碼點放入大括號即能正確讀取該字符
"\uD842\uDFB7"
// "𠮷"
由於超過0xFFFF的數值會被理解成\u20BB+7,又\u20BB爲不可打印字符,所有顯示一個空格加7
"\u20BB7"
// " 7"
加大括號後讀取正常
"\u{20BB7}"
// "𠮷"
"\u{41}\u{42}\u{43}"
// "ABC"
let hello = 123;
hell\u{6F} // 123
'\u{1F680}' === '\uD83D\uDE80'
// true
- ES6則有6種方法表示一個字符
'\z' === 'z' // true
'\172' === 'z' // true
'\x7A' === 'z' // true
'\u007A' === 'z' // true
'\u{7A}' === 'z' // true
2. 字符串的遍歷器接口
ES6爲字符串添加了遍歷器接口,使得可以被for…of循環遍歷
(1)可以被for…of循環遍歷
(2)for…of還能識別大於0xFFFF的碼點,傳統for循環無法識別
(1)
for (let codePoint of 'foo') {
console.log(codePoint)
}
// "f"
// "o"
// "o"
(2)傳統for認爲包含兩個字符
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);
}
// "𠮷"
3. 直接輸入U+2028和U+2029
JS允許在字符串輸入字符的轉義形式。即Unicode碼點=>\u4e2d
但有5個字符不能再字符串裏直接使用
U+005C:反斜槓(reverse solidus)
U+000D:回車(carriage return)
U+2028:行分隔符(line separator)
U+2029:段分隔符(paragraph separator)
U+000A:換行符(line feed)
如:反斜槓需寫成\或者\u005c
但JSON支持U+2028(行分隔符)和 U+2029(段分隔符)。即json格式轉換爲字符串後的這兩個字符剛好是字符串不允許使用的==>報錯
const json = '"\u2028"';
JSON.parse(json); // 可能報錯
- 解決…是ES2019已允許字符串中輸入這兩字符。
- 但正則表達式不允許直接輸入這兩字符。
- 不過JSON本就不允許包含正則。
4. JSON.stringify()的改造
- 說明
據標準,JSON數據必須是UTF-8編碼。
又UTF-8編碼規定0xD800到0xDFFFF之間的碼點不能單獨使用,必須配對使用。 - 存在的問題:JSON.stringify()可能返回oxD800到0xDFFFF之間的單個碼點
- 解決是…ES2019遇到這個範圍的碼點將返回轉義字符串待開發者處理
ES2019之前
JSON.stringify('\u{D834}') // "\u{D834}"
ES2019
JSON.stringify('\u{D834}') // ""\\uD834""
JSON.stringify('\uDF06\uD834') // ""\\udf06\\ud834""
5. 模板字符串
- 優勢
非模板字符串
$('#result').append(
'There are <b>' + basket.count + '</b> ' +
'items in your basket, ' +
'<em>' + basket.onSale +
'</em> are on sale!'
);
ES6模板字符串
$('#result').append(`
There are <b>${basket.count}</b> items
in your basket, <em>${basket.onSale}</em>
are on sale!
`);
- 模板字符串中的所有html標籤、換行、縮進都會保留
$('#list').html(`
<ul>
<li>first</li>
<li>second</li>
</ul>
`);
- 消除行號方法
$('#list').html(`
<ul>
<li>first</li>
<li>second</li>
</ul>
`.trim());
- 模板字符串中使用變量${}。同時{}還能放表達式、對象屬性、函數。進而能嵌套使用
let x = 1;
let y = 2;
`${x} + ${y} = ${x + y}`
// "1 + 2 = 3"
`${x} + ${y * 2} = ${x + y * 2}`
// "1 + 4 = 5"
let obj = {x: 1, y: 2};
`${obj.x + obj.y}`
// "3"
function fn() {
return "Hello World";
}
`foo ${fn()} bar`
// foo Hello World bar
- 如使用反引號則需使用反斜槓轉義
let greeting = `\`Yo\` World!`;
6. 實例:模板編譯
- 通過模板字符串生成正式模板
echo('<ul>');
for(let i=0; i < data.supplies.length; i++) {
echo('<li>');
echo(data.supplies[i]);
echo('</li>');
};
echo('</ul>');
- 輸出轉換爲JS表達式字符串
模板編譯函數
function compile(template){
const evalExpr = /<%=(.+?)%>/g;
const expr = /<%([\s\S]+?)%>/g;
template = template
.replace(evalExpr, '`); \n echo( $1 ); \n echo(`')
.replace(expr, '`); \n $1 \n echo(`');
template = 'echo(`' + template + '`);';
let script =
`(function parse(data){
let output = "";
function echo(html){
output += html;
}
${ template }
return output;
})`;
return script;
}
編譯模板
let parse = eval(compile(template));
div.innerHTML = parse({ supplies: [ "broom", "mop", "cleaner" ] });
// <ul>
// <li>broom</li>
// <li>mop</li>
// <li>cleaner</li>
// </ul>
7. 標籤模板
標籤模板其實不是模板,而是函數調用的一種特殊形式。
“標籤”指定的是函數,後面的模板字符串就是參數。
如何使用
- 簡單示例
alert`123`
// 等同於
alert(123)
- 函數後的模板字符串含有變量的情況
(1)會變成多個參數。
let a = 5;
let b = 10;
tag`Hello ${ a + b } world ${ a * b }`;
// 等同於。變量替換成員間隔即x和x+2之間(最後的''是因爲最後一個變量後面沒成員)。其他參數則是變量計算後的值
tag(['Hello ', ' world ', ''], 15, 50);
(2)
主要用途
- 過濾HTML字符串如防止用戶惡意操作
let message =
SaferHTML`<p>${sender} has sent you a message.</p>`;
function SaferHTML(templateData) {
let s = templateData[0];
for (let i = 1; i < arguments.length; i++) {
let arg = String(arguments[i]);
// Escape special characters in the substitution.
s += arg.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
// Don't escape special characters in the template.
s += templateData[i];
}
return s;
}
let sender = '<script>alert("abc")</script>'; // 惡意代碼
let message = SaferHTML`<p>${sender} has sent you a message.</p>`;
message
// <p><script>alert("abc")</script> has sent you a message.</p>
- 多語言(國際化)轉換。(模板字符串沒有條件判斷和循環處理,但通過標籤(函數)模板則可實現)
i18n`Welcome to ${siteName}, you are visitor number ${visitorNumber}!`
// "歡迎訪問xxx,您是第xxxx位訪問者!"
// 下面的hashTemplate函數
// 是一個自定義的模板處理函數
let libraryHtml = hashTemplate`
<ul>
#for book in ${myBooks}
<li><i>#{book.title}</i> by #{book.author}</li>
#end
</ul>
`;
- 嵌套其他語言(編程)
(1)將DOM字符串轉爲React對象。jsx
https://gist.github.com/lygaret/a68220defa69174bdec5
jsx`
<div>
<input
ref='input'
onChange='${this.handleChange}'
defaultValue='${this.state.value}' />
${this.state.value}
</div>
`
- 標籤(函數)模板處理的第一個參數(由非變量即字符串組成)有個raw屬性。
raw和第一個參數內容完全一致,除了raw的\都被轉義了(\n變\n)
console.log`123`
// ["123", raw: Array[1]]
tag`First line\nSecond line`
function tag(strings) {
console.log(strings.raw[0]);
// strings.raw[0] 爲 "First line\\nSecond line"
// 打印輸出 "First line\nSecond line"
}
8.模板字符串的限制
- 限制是模板字符串默認會把字符串轉義==>導致無法嵌入其他語言
function latex(strings) {
// ...
}
let document = latex`
\newcommand{\fun}{\textbf{Fun!}} // 正常工作
\newcommand{\unicode}{\textbf{Unicode!}} // 報錯
\newcommand{\xerxes}{\textbf{King!}} // 報錯
Breve over the h goes \u{h}ere // 報錯
`
- 解決…ES2018放鬆了對模板字符串轉義的限制,如遇到不合法的字符串轉義則返回undefined,而不是報錯。但raw屬性上可以得到原始字符串!(僅針對模板字符串)
function tag(strs) {
strs[0] === undefined
strs.raw[0] === "\\unicode and \\u{55}";
}
tag`\unicode and \u{55}`