Tagged Template
Learn the functions, uses, and perks of tagged templates.
A template literal may be untagged or tagged.
Tags
Tags are functions that receive the contents of the provided template literal in two parts:
- The template object
- The evaluated expressions
The template literals you have seen so far are untagged, but we have the option of placing a tag in front of a template literal.
Built-in tagged template function raw()
Before you learn how to write your own tagged template functions, let’s use a built-in tagged template function called raw()
. Suppose we want to create a string with some embedded special characters.
In the next example, we create a regular string, but we escape each special character with a backslash.
'use strict';//START:ONEconsole.log('some special characters: \\ \\n \\b \'');//END:ONE
The string captures all the special characters in the output, but creating those characters required repetitive use of \
before each special character. Let’s ...