Sub topic 14
Tagged Templates and String.raw
This chapter assumes you already know template literals and ${} interpolation from the earlier chapter. It also assumes you are comfortable with rest parameters (...values) and Array.prototype.reduce.
What a Tag Does
A tagged template is a template literal with a function name in front of it, like `shouthi ${name}! `. JavaScript does not build the string itself. It calls the function instead and passes it two things:
stringsis an array of the literal text pieces between the substitutions....valuesholds the evaluated${}expressions, in order.
The strings array always has exactly one more element than values. If a template starts or ends with a substitution, the first or last piece is an empty string. The tag can return anything, including a value that is not a string.
Writing a Tag Function
The usual pattern interleaves the pieces and the values. You transform each value on the way through:
function shout(strings, ...values) {
return strings.reduce(
(out, str, i) => out + str + (i < values.length ? String(values[i]).toUpperCase() : ""),
""
);
}
console.log(shout`hi ${"ada"}!`); // hi ADA!A more practical tag escapes HTML. The literal parts are trusted markup that you wrote, and the values may come from users:
const ESCAPES = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
function html(strings, ...values) {
const escape = (v) => String(v).replace(/[&<>"']/g, (c) => ESCAPES[c]);
return strings.reduce(
(out, str, i) => out + str + (i < values.length ? escape(values[i]) : ""),
""
);
}
const name = "<b>Ada</b>";
console.log(html`<p>Hello, ${name}</p>`); // <p>Hello, <b>Ada</b></p>Cooked and Raw Strings
Each piece of text exists in two forms. strings[i] is the cooked form, with escape sequences already processed. strings.raw[i] is the text exactly as typed in the source.
function show(strings) {
console.log(JSON.stringify(strings[0]), JSON.stringify(strings.raw[0]));
}
show`a\nb`; // "a\nb" "a\\nb" (cooked has a real newline, raw has a backslash and n)
show`\unicode`; // undefined "\\unicode"String.raw
String.raw is a built-in tag that joins the raw pieces with the values. It is useful for Windows paths and regex sources, where you want backslashes kept as written:
console.log(String.raw`C:\new\folder`); // C:\new\folder
const n = 5;
console.log(String.raw`\d{${n}}`); // \d{5}
console.log(new RegExp(String.raw`^\d{${n}}$`).test("12345")); // true
// It can also be called as a plain function with a { raw } object:
console.log(String.raw({ raw: ["a", "b", "c"] }, 1, 2)); // a1b2cCommon Mistakes
| Mistake | Fix |
|---|---|
| Looping over `values` and dropping the last string piece | Loop over `strings`, which always has one extra element |
| Escaping the literal parts as well as the values | Escape only `values`, because the literal parts are your own markup |
| Expecting `String.raw` to keep a backslash right before the closing backtick | It can't: `` `\` `` escapes the backtick itself |
Exercise
Given function t(s, ...v) { return [s.length, v.length]; }, what does t${1}${2} return, and what does the strings array contain?
Show answer
It returns [3, 2]. The strings array is ["", "", ""], with empty pieces before, between, and after the two substitutions, because strings always has one more element than values.
Exercise
Write a tag currency that formats every numeric value with two decimals (using toFixed(2)) and leaves other values unchanged, so that currencyTotal: ${4.5} for ${"Ada"} returns "Total: 4.50 for Ada".
Show answer
function currency(strings, ...values) { return strings.reduce((out, str, i) => { if (i >= values.length) return out + str; const v = values[i]; return out + str + (typeof v === "number" ? v.toFixed(2) : String(v)); }, ""); }