Sub topic 3
Tagged Templates and Tag Functions
This chapter assumes you already know ${} interpolation, rest parameters, and Array.prototype.reduce.
How a Tag Function Receives Its Arguments
When you put a function name directly before a template literal, JavaScript calls that function instead of building a string. This function is called a tag. Its first argument is an array of the literal string parts. The evaluated substitutions arrive as the remaining arguments. The strings array always has one more element than there are values, so it can hold an empty string at either end.
function tag(strings, ...values) {
console.log(strings); // [ 'a', ' b ', '' ]
console.log(values); // [ 1, 2 ]
return strings.reduce(
(out, str, i) => out + str + (i < values.length ? `[${values[i]}]` : ""),
""
);
}
console.log(tag`a${1} b ${2}`); // a[1] b [2]The tag can return anything it likes. The return value does not have to be a string.
Raw Strings and String.raw
Each string part comes in two forms. The cooked form is the one with escapes already processed. The raw form, strings.raw, is the source text exactly as typed. The built-in tag String.raw joins the raw parts, which makes it handy for Windows paths and regular expressions.
console.log(String.raw`C:\new\table`); // C:\new\table
function firstRaw(strings) {
return strings.raw[0];
}
console.log(firstRaw`\n`.length); // 2Building an Escaping Tag
A plain template literal inserts values unchanged. If you interpolate user input into HTML that way, you open the door to injection. An escaping tag can sanitize every value before it joins the parts together:
function html(strings, ...values) {
const escape = (s) => String(s)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
return strings.reduce((out, str, i) => out + escape(values[i - 1]) + str);
}
console.log(html`<p>${"<script>"}</p>`); // <p><script></p>Template Object Caching per Call Site
Every time a given tagged template in your source runs, it passes the same strings array, and that array is frozen. Libraries take advantage of this by using the array as a cache key for parsed templates.
function id(strings) { return strings; }
const results = [];
for (let i = 0; i < 2; i++) results.push(id`x`);
console.log(results[0] === results[1]); // true
console.log(Object.isFrozen(results[0])); // trueInvalid Escapes in Tagged Templates
Since ES2018, a tagged template accepts an invalid escape such as \unicode. When it does, the cooked string for that part is undefined and the raw text is still there. In an untagged template the same escape is a SyntaxError.
function parts(strings) {
return [strings[0], strings.raw[0]];
}
console.log(parts`\unicode`); // [ undefined, '\\unicode' ]Exercise
For the call tag${x}, how many elements does the strings array have, and what are they?
Show answer
It has two elements, both empty strings: [ '', '' ]. The strings array always has one more element than the values.
Exercise
Why does html<a href="${url}"> not protect against a value like "javascript:alert(1)"?
Show answer
The tag only escapes HTML special characters. The value contains none of them, so it passes through unchanged and still works as a URL scheme. URL contexts need separate validation.