JavaScript 字符串模板
同義詞:
- Template Literals
- Template Strings
- String Templates
- Back-Tics 語法
插值
模板字面量提供了一種將變量和表達式插入字符串的簡單方法。
該方法稱為字符串插值(string interpolation)。
語法
${...}
變量替換
模板字面量允許字符串中的變量:
實例
let firstName = "Bill"; let lastName = "Gates"; let text = `Welcome ${firstName}, ${lastName}!`;
用真實值自動替換變量稱為字符串插值。
表達式替換
模板字面量允許字符串中的表達式:
實例
let price = 10; let VAT = 0.25; let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;
用真實值自動替換表達式稱為字符串插值。
HTML 模板
實例
let header = "Templates Literals"; let tags = ["template literals", "javascript", "es6"]; let html = `<h2>${header}</h2><ul>`; for (const x of tags) { html += `<li>${x}</li>`; } html += `</ul>`;
瀏覽器支持
Internet Explorer 不支持模板字面量。
第一個完全支持模板字面量的瀏覽器版本是:
Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome 41 | Edge 13 | Firefox 34 | Safari 10 | Opera 29 |
2015 年 3 月 | 2015 年 11 月 | 2014 年 12 月 | 2016 年 9 月 | 2015 年 4 月 |