Sub topic 14
Tagged Templates and String.raw
This chapter assumes you already know template literals and ${} interpolation (covered earlier), rest parameters (...values), and Array.prototype.reduce. You should also be comfortable running snippets in Node.js or a browser console.
A plain template literal always produces a string. If you put a function name directly in front of the literal, JavaScript calls that function instead, and the function decides the result. That function is called a tag, and the whole expression is a tagged template. String.raw is a tag built into the language. It returns the literal text with backslashes left exactly as you typed them.
How a Tag Function Is Called
A tag function receives two kinds of input:
- A
stringsarray holding the literal text pieces between the substitutions. - The evaluated substitution values, passed as separate arguments. Most tags collect them with a rest parameter.
function inspect(strings, ...values) {
console.log(strings); // [ 'a', ' b ', '' ]
console.log(strings.raw); // [ 'a', ' b ', '' ]
console.log(values); // [ 1, 2 ]
return "done";
}
const result = inspect`a${1} b ${2}`;
console.log(result); // doneThere is always one more string than there are values (strings.length === values.length + 1). If the literal starts or ends with a substitution, the matching string piece is an empty string "". That rule lets every tag use the same loop: start with strings[0], then append each value followed by the next string.
The tag can be any expression that evaluates to a function: an identifier (html), a member access (db.sql), or a call that returns a function (makeTag("en")). Optional chaining cannot be used as a tag, so `obj?.tagx is a SyntaxError`.
Cooked Strings Versus Raw Strings
Each piece of text exists in two forms. The cooked form in strings[i] has escape sequences already processed. The raw form in strings.raw[i] is the source text exactly as written.
function both(strings) {
return { cooked: strings[0], raw: strings.raw[0] };
}
const r = both`line1\nline2`;
console.log(r.cooked.length); // 11 (\n became one newline character)
console.log(r.raw.length); // 12 (backslash and n kept)
console.log(r.raw); // line1\nline2| Source text | Cooked (`strings[i]`) | Raw (`strings.raw[i]`) |
|---|---|---|
| `\n` | one newline character | backslash followed by `n` |
| `\u0041` | `A` | `\u0041` |
| `` \` `` | a backtick | backslash followed by a backtick |
| `\unicode` (invalid escape) | `undefined` | `\unicode` |
| a CRLF line break in the source | `\n` | `\n` (also normalized) |
Invalid escapes are allowed only in tagged templates
An untagged template such as ` \unicode is a SyntaxError, because \u must be followed by a valid Unicode escape. Since ES2018, a tagged template accepts it. The cooked value is set to undefined` and the raw value keeps the text. This lets tags handle content such as LaTeX or Windows paths, where backslashes are common.
function show(strings) {
return [strings[0], strings.raw[0]];
}
console.log(show`\unicode`); // [ undefined, '\\unicode' ]The strings Array Is Frozen and Cached
The strings array and its raw array are frozen. JavaScript also creates the array once per call site, meaning one place in the source code, and passes the same object every time that site runs.
function id(strings) {
return strings;
}
const seen = [];
for (let i = 0; i < 2; i++) {
seen.push(id`x${i}`);
}
console.log(seen[0] === seen[1]); // true (same call site)
console.log(Object.isFrozen(seen[0])); // true
console.log(id`x${0}` === id`x${0}`); // false (two different call sites)Libraries use this behaviour. You can store work done on the static text, such as a parsed HTML template or a compiled query, in a WeakMap keyed by strings. On later runs the tag reuses that work and only processes the new values.
Tags That Do Real Work
Escaping values for HTML
The literal text comes from the developer, so you can trust it. The values may come from users, so they should be escaped. A tag can treat the two differently because it receives them separately.
const escapeHtml = (value) =>
String(value)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
function html(strings, ...values) {
let out = strings[0];
for (let i = 0; i < values.length; i++) {
out += escapeHtml(values[i]) + strings[i + 1];
}
return out;
}
const name = '<img src=x onerror="alert(1)">';
console.log(html`<p>Hello, ${name}</p>`);
// <p>Hello, <img src=x onerror="alert(1)"></p>The & replacement must come first. Otherwise it would also rewrite the & characters produced by the later replacements.
Returning something other than a string
A tag can return any value. This tag builds a parameterized query object. The values never enter the SQL text, which blocks SQL injection when you pass the object to a database driver.
function sql(strings, ...values) {
return {
text: strings.reduce((acc, str, i) => acc + "$" + i + str),
values,
};
}
const userId = 42;
const query = sql`SELECT * FROM users WHERE id = ${userId} AND status = ${"active"}`;
console.log(query.text); // SELECT * FROM users WHERE id = $1 AND status = $2
console.log(query.values); // [ 42, 'active' ]reduce is called without an initial value, so acc starts as strings[0] and the index i starts at 1. That gives placeholders numbered from $1, which is the PostgreSQL style.
String.raw
String.raw is a built-in tag. It joins strings.raw with the substitution values, so escape sequences are not processed but ${} still is.
console.log(String.raw`C:\new\table`); // C:\new\table
console.log(String.raw`total: ${1 + 1}\n`); // total: 2\n
const re = new RegExp(String.raw`^\d+\.\d+$`);
console.log(re.test("3.14")); // true
console.log(re.source); // ^\d+\.\d+$Without String.raw, the regex source would need doubled backslashes: "^\\d+\\.\\d+$". That is the most common practical use. Others are Windows paths and test fixtures that contain literal escape text.
Calling String.raw as a function
You can call String.raw directly by passing an object with a raw property, followed by the values. The raw value can be an array or any array-like value, including a string.
console.log(String.raw({ raw: ["a", "b", "c"] }, 1, 2)); // a1b2c
console.log(String.raw({ raw: "xyz" }, "-", "-")); // x-y-zString.raw edge cases
- `
String.raw\is aSyntaxError. The backslash escapes the closing backtick, so the literal never ends. Use"\\"` to get a single backslash. - `
String.rawa\b`returnsa\b ``. The backslash stays in the result, so you cannot write a lone backtick this way. ${cannot appear literally even in raw mode. Write\${and the result keeps the backslash: `String.raw\${x}returns\${x}`.- Line breaks are normalized: CRLF or CR in the source becomes
\nin the raw string as well.
Choosing Between the Options
| Need | Use |
|---|---|
| Insert values into text | An untagged template literal |
| Keep backslashes literally (regex, paths) | `String.raw` |
| Treat values differently from literal text (escaping, translation lookups, query parameters) | A custom tag |
| Produce a non-string result such as a DOM node or query object | A custom tag |
| Cache work on the static text | A custom tag with a `WeakMap` keyed by `strings` |
A custom tag only protects you when callers use it. Writing html(userInput) or concatenating strings before the tag runs bypasses the escaping completely.
Exercise
Write a tag upper so that upperHello ${"ada"}, you have ${3} messages returns "Hello ADA, you have 3 messages". Values are converted to strings and upper-cased, and the literal text is unchanged.
Show answer
function upper(strings, ...values) { return strings.reduce((out, str, i) => out + String(values[i - 1]).toUpperCase() + str); } Because reduce has no initial value, it starts with strings[0], and each later piece strings[i] is preceded by values[i - 1]. String(3).toUpperCase() is "3", so the number is unchanged.
Exercise
What do these log, and why? (1) console.log(String.rawa\tb.length) (2) function f(s) { return s[0]; } console.log(f\xZZ) (3) console.log(\xZZ)
Show answer
(1) 4, because String.raw keeps the backslash and the t as two characters. (2) undefined, because \xZZ is an invalid hex escape: a tagged template allows it but sets the cooked string to undefined. (3) The script fails with a SyntaxError before it runs, because untagged templates do not allow invalid escapes.
Exercise
A tag stores parsed templates in a WeakMap keyed by its strings argument. Why does a call inside a loop hit the cache on every iteration after the first, while two identical-looking tagged templates on different lines do not share an entry?
Show answer
JavaScript creates one frozen strings array per call site, meaning per location in the source code, and reuses it every time that site is evaluated. A loop runs the same call site again, so the key is the same object. Two literals on different lines are separate call sites with separate array objects, even if their text is identical.