[ECMAScript] Tagged template literals

Template lieterals

Template literals是一個(gè)ES2015特性,它使用反引號(hào)包含一個(gè)字符串字面量,并且支持嵌入表達(dá)式和換行。

> console.log(`1
2`);

> 1 
2

> console.log(`hello ${window.name}`);
> hello [object window]

\\$\ `需要轉(zhuǎn)義:

> console.log(`\\
\`
\$`);

> \
`
$

Tagged template literals

Template lieterals支持Tag。
我們可以在Template lieterals前放置一個(gè)函數(shù)名,用來控制它如何被轉(zhuǎn)換成字符串

foo`...`

該函數(shù)的第一個(gè)參數(shù),是組成Template lieterals的由各個(gè)嵌入表達(dá)式分隔的字符串?dāng)?shù)組,剩余參數(shù)分別是各個(gè)嵌入表達(dá)式的值。

const myTag = (strs, ...exprs) => {
    console.log(strs);                  //["x", "\y", ""]
    console.log(strs.raw);              //["x", "\\y", ""]

    console.log(exprs);                 //[1, 2]

    console.log(strs[1].length);        //2
    console.log(strs.raw[1].length);    //3

    return +new Date;
};

const obj = { a: 1, b: 2 };

const result = myTag`x${obj.a}\\y${obj.b}`;
console.log(result);

注:
(1)Tag函數(shù)可以返回任意對(duì)象,不一定是字符串。
(2)strs有3個(gè)元素而不是2個(gè),因?yàn)?code>${obj.a}和${obj.b}將字符串x${obj.a}y${obj.b}分隔成3個(gè)部分,"x""\y",以及尾部的空字符串""
(3)strs確實(shí)是一個(gè)數(shù)組,但是它還有一個(gè)raw屬性。其屬性值strs.raw也是一個(gè)數(shù)組,其元素分別表示strs中對(duì)應(yīng)的,經(jīng)過轉(zhuǎn)義之前的在Template literals中由用戶輸入的字符串。例如,上例中"\y"未轉(zhuǎn)義之前對(duì)應(yīng)的字符串為"\\\\y",顯然這兩個(gè)字符串長(zhǎng)度是不同的。

> ((strs, ...exprs) => 
    console.log(strs[0].length, strs.raw[0].length)) `\\`;

> 1 2

String.raw

String.raw是ES2015,內(nèi)置對(duì)象String的一個(gè)靜態(tài)方法,
把它作為Tag,可以做到只替換嵌入表達(dá)式而不轉(zhuǎn)義字符。

const raw = String.raw`1\\2\\${1+2}`;

console.log(raw);           //1\\2\\3
console.log(raw.length);    //7

const x = `1\\2\\${1+2}`;
console.log(x);             //1\2\3
console.log(x.length);      //5

Escape problem

Template literals遵從字符串的轉(zhuǎn)義規(guī)則:
(1)以\u開頭,后跟4個(gè)16進(jìn)制數(shù)字,例如,\u00B1表示±
(2)以\u開頭,使用大括號(hào)括起來的16進(jìn)制數(shù)字,例如,\u{2F804}表示
(3)以\x開頭,后跟2個(gè)16進(jìn)制數(shù)字,例如,\xB1表示±
(4)以\\開頭,后跟10進(jìn)制數(shù)字,用來表示八進(jìn)制字面量(注:strict mode下不支持)

解釋器遇到\u\x,如果發(fā)現(xiàn)后面的字符不滿足以上條件,就會(huì)報(bào)語法錯(cuò)。例如,

> latex`\unicode`
> Uncaught SyntaxError: Invalid Unicode escape sequence

Lifting template literal restriction

Tagged tamplate literals經(jīng)常用來實(shí)現(xiàn)DSL,
例如,可以用ECMAScript實(shí)現(xiàn)LaTeX

function latex(strings) {
  // ...
}

let document = latex`
\newcommand{\fun}{\textbf{Fun!}}  // works just fine
\newcommand{\unicode}{\textbf{Unicode!}} // Illegal token!
\newcommand{\xerxes}{\textbf{King!}} // Illegal token!

Breve over the h goes \u{h}ere // Illegal token!
`

這些DSL中不可避免的會(huì)包含一些以\u或者\x開頭的字符串,作為該DSL內(nèi)部的轉(zhuǎn)義序列,這些情況下Tagged template literals也無能為力。

Lifting template literal restriction就是一個(gè)改善這個(gè)問題的TC39提案,目前已經(jīng)出于Finished Proposals階段了,即最終會(huì)被加入到ES2018規(guī)范中。

注:
(1)去除\u或者\x的限制,只適用于Tagged template literals,而對(duì)于untagged template literals無效,仍然會(huì)報(bào)語法錯(cuò)。
(2)為了兼容性,該提案只是將轉(zhuǎn)義后的字符串?dāng)?shù)組strs,置為單元素?cái)?shù)組[undefined],tag函數(shù)需要手動(dòng)處理strs.raw進(jìn)行處理。

> ((strs, ...exprs) => {
    console.log(strs);
    console.log(strs.raw);
}) `something else \unicode`;

> [undefined]
> ["something else \unicode"]

References

MDN - Template lieterals
MDN - String.raw
tc39/proposals: Finished Proposals
Template Literal Revision

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容