JavaScript Template Literals
Synonyms:
- Template Literals
- Template Strings
- String Templates
- Back-Tics Syntax
Back-Tics Syntax
Template Literals use back-ticks (``) rather than the quotes ("") to define a string:
Quotes Inside Strings
With template literals, you can use both single and double quotes inside a string:
Multiline Strings
Template literals allows multiline strings:
Interpolation
Template literals provide an easy way to interpolate variables and expressions into strings.
The method is called string interpolation.
The syntax is:
${...}
Variable Substitutions
Template literals allow variables in strings:
例子
let firstName = "John";
let lastName = "Doe";
let text = `Welcome ${firstName}, ${lastName}!`;
亲自尝试 »
Automatic replacing of variables with real values is called string interpolation.
Expression Substitution
Template literals allow expressions in strings:
Automatic replacing of expressions with real values is called string interpolation.
HTML Templates
例子
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>`;
亲自尝试 »
浏览器支持
Template Literals
is an ES6 feature (JavaScript 2015).
所有现代浏览器都支持它:
铬合金 | 边缘 | 火狐 | 苹果浏览器 | 歌剧 |
是的 | 是的 | 是的 | 是的 | 是的 |
Template Literals
Internet Explorer 不支持。