JavaScript Template Strings
Template strings in JavaScript are a convenient string syntax that allows you to embed expressions and variables in strings.
Template strings use backticks``as the delimiter of the string literal.
Template literals are literals delimited with backticks (`), allowing multi-line strings, string interpolation with embedded expressions, and a special structure called tagged templates.
Syntax
`string text`
`string text line 1
string text line 2`
`string text ${expression} string text`
tagFunction`string text ${expression} string text`
Parameters
string text: The string text that will become part of the template literal. Almost all characters are allowed, including line breaks and other whitespace characters. However, unless a tag function is used, invalid escape sequences will cause syntax errors.
-
expression: The expression to be inserted at the current position, whose value is converted to a string or passed to tagFunction.
-
tagFunction: If specified, it will be called with the array of template strings and substitution expressions, and the return value becomes the value of the template literal.
Browser Support
Template literals are a new ES6 feature (JavaScript 2015), and are currently supported by some of the latest browsers:
| Chrome | Edge | Firefox | Safari | Opera |
| Supported | Supported | Supported | Supported | Supported |
You can use both single quotes and double quotes in template strings:
Template strings also support multi-line text without the need for special escape characters:
To escape a backtick in a template literal (`), you need to add a backslash before the backtick (\)。
`\`` === "`"; // true
Template literals are enclosed by backticks (`) instead of double quotes (") or single quotes (')。
In addition to ordinary strings, template literals can also contain placeholders—an embedded expression delimited by a dollar sign and curly braces:${expression}。
The string and placeholders are passed to a function (either the default function or a custom function). The default function (when no custom function is provided) simply performs string interpolation to replace placeholders, and then concatenates these parts into a single string.
Template strings allow us to use variables:
Examples
Try it Yourself »
In the examples above,${name}and${age}are the expression parts of the template string, which are contained in${}inside, and are evaluated at runtime.
Template strings allow you to reference variables, make function calls, and perform arbitrary JavaScript expressions in the string.
Template strings allow us to use expressions:
Examples
let VAT = 0.25;
let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;
Try it Yourself »
Use template strings as HTML templates:
Examples
let tags = ["EXAMPLE", "GOOGLE", "TAOBAO"];
let html = `<h2>${header}</h2><ul>`;
for (const x of tags) {
html += `<li>${x}</li>`;
}
html += `</ul>`;
Try it Yourself »