#
模板字符串允許嵌入表達式,並且支持多行字符串和字符串插補特性。
`string text`
`string text line 1
string text line 2`
`string text ${expression} string text`
tag `string text ${expression} string text`
模板字符串使用反引號 (` `) 來代替普通字符串中的用雙引號和單引號。
模板字符串可以包含特定語法(${expression})的占位符。
占位符中的表達式和周圍的文本會一起傳遞給一個默認函數,
該函數負責將所有的部分連接起來,如果一個模板字符串由表達式開頭,
則該字符串被稱為帶標簽的模板字符串,該表達式通常是一個函數,
它會在模板字符串處理后被調用,在輸出最終結果前,
你都可以在通過該函數對模板字符串來進行操作處理。
#多行字符串
//原始 console.log("string text line 1\n\string text line 2"); // "string text line 1 // string text line 2" //模板字符串 console.log(`string text line 1 string text line 2`); // "string text line 1 // string text line 2"
#表達式插補
//原始 var a = 5; var b = 10; console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + "."); // "Fifteen is 15 and // not 20." //模板字符串 var a = 5; var b = 10; console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`); // "Fifteen is 15 and // not 20."
#帶標簽的模板字符串
var a = 5; var b = 10; function tag(strings, ...values) { console.log(strings[0]); // "Hello " console.log(strings[1]); // " world " console.log(values[0]); // 15 console.log(values[1]); // 50 return "Bazinga!"; } console.log(tag `Hello ${ a + b } world ${ a * b}`); // "Bazinga!"
#在標簽函數的第一個參數中,存在一個特殊的屬性raw ,
可以通過它來訪問模板字符串的原始字符串。
function tag(strings, ...values) { console.log(strings.raw[0]); // "string text line 1 \n string text line 2" } tag `string text line 1 \n string text line 2`;
#安全性
由於模板字符串能夠訪問變量和函數,因此不能由不受信任的用戶來構造。
`${console.warn("this is",this)}`; // "this is" Window let a = 10; console.warn(`${a+=20}`); // "30" console.warn(a); // 30
#