模板字符串(template string)是增強版的字符串,用反引號(`)標識。它可以當作普通字符串使用,也可以用來定義多行字符串,或者在字符串中嵌入變量。
一.模板字符串
1.基本使用
-
使用反引號(`)做標識,可以定義多行字符串,在字符串中使用${}嵌入變量。在模板字符串中的任何變量最終都會變爲String類型輸出。
// 普通字符串 `In JavaScript '\n' is a line-feed.` // 多行字符串 `In JavaScript this is not legal.` console.log(`string text line 1 string text line 2`); // 字符串中嵌入變量 let name = "Bob", time = "today"; `Hello ${name}, how are you ${time}?`
①.特點-與傳統輸出模板相比
-
傳統的 JavaScript 語言,輸出模板。
$('#result').append( 'There are <b>' + basket.count + '</b> ' + 'items in your basket, ' + '<em>' + basket.onSale + '</em> are on sale!' );
-
使用模板字符串。
$('#result').append(` There are <b>${basket.count}</b> items in your basket, <em>${basket.onSale}</em> are on sale! `);
②.特點-模板字符串中使用反引號
-
若在模板字符串中需要使用到反引號,則前面要用反斜槓轉義。
let greeting = `\`Yo\` World!`;
③.特點-輸出多行字符串
-
如果使用模板字符串表示多行字符串,所有的空格和縮進都會被保留在輸出之中。
$('#list').html(` <ul> <li>first</li> <li>second</li> </ul> `);
④.特點-在${}中調用表達式,調用函數,嵌入變量
-
模板字符串中嵌入變量,需要將變量名寫在${}之中。
function authorize(user, action) { if (!user.hasPrivilege(action)) { throw new Error( // 傳統寫法爲 // 'User ' // + user.name // + ' is not authorized to do ' // + action // + '.' `User ${user.name} is not authorized to do ${action}.`); } }
-
大括號內部可以放入任意的 JavaScript 表達式,可以進行運算,以及引用對象以及對象屬性。若引用的是對象則會調用對象的toString方法。
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 func = (name) => `Hello ${name}!`; func('Jack') // "Hello Jack!" //同如下範例 let func = function (name) { return `Hello ${name}!`; } console.log(func('guys!'))
-
大括號內部是一個字符串,將會原樣輸出;變量沒有聲明就會報錯。
`Hello ${'World'}` // "Hello World" // 變量place沒有聲明 let msg = `Hello, ${place}`; // 報錯
⑤.特點-模板字符串嵌套
-
模板字符串嵌套使用。
const tmpl = addrs => ` <table> ${addrs.map(addr => ` <tr><td>${addr.first}</td></tr> <tr><td>${addr.last}</td></tr> `).join('')} </table> `; //調用 const data = [ { first: '<Jane>', last: 'Bond' }, { first: 'Lars', last: '<Croft>' }, ]; console.log(tmpl(data)); // <table> // // <tr><td><Jane></td></tr> // <tr><td>Bond</td></tr> // // <tr><td>Lars</td></tr> // <tr><td><Croft></td></tr> // // </table>