Summary: in this tutorial, you will learn about JavaScript template literal, which allows you to work with a string template more easily. Show Before ES6, you use single quotes ( To enable you to solve more complex problems, ES6 template literals provide the syntax that allows you to work with strings more safely and cleanly. In ES6, you create a template literal by wrapping your text in backticks (
and you get the following features:
The basic syntax of JavaScript template literalsAs mentioned earlier, instead of using the single quotes or double quotes, a template literal uses backticks, as shown in the following example:
Using the backticks, you can freely use the single or double quotes in the template literal without escaping.
If a string contains a backtick, you must escape it using a backslash (
Multiline stringsBefore ES6, you use the
following technique to create a multi-line string by manually including the newline character (
Note that the backslash ( This technique, however, is not consistent across JavaScript engines. Therefore, it was pretty common to create a multiline string that relies on an array and string concatenation as follows:
The template literals allow you to define multiline strings more easily because you need to add a new line in the string wherever you want:
Note that the whitespace is a part of the string. Therefore, you need to ensure that the text lines up with proper indentation. Suppose you have a
The following code
returns the HTML code of the
The following is the output of the variable
Variable and expression substitutionsAt this point, a template literal is just like a better version of a regular JavaScript string. The big difference between a template literal and a regular string is substitutions. The substitutions allow you to embed variables and expressions in a string. The JavaScript engine will automatically replace these variables and expressions with their values. This feature is known as string interpolation. To instruct JavaScript to substitute a variable and expression, you place the variable and expression in a special block as follows:
See the following example:
The substitution The
Tagged templatesA template tag carries the transformation on the template literal and returns the result string. You place the tag at the beginning of the template before the backtick (`) character as follows:
In this example,
In this function:
See the following example:
In this example, the The first argument is the
The second argument is Summary
Was this tutorial helpful ? |