Sub topic 2
Cooked and Raw Strings
This chapter assumes you know how a tag function receives a strings array and the substitution values, and that you can use Array.prototype.reduce.
Cooked and Raw Strings
Each static part of a template has two forms. The cooked form has escape sequences processed, so \n becomes a real newline. The raw form keeps the characters exactly as you typed them. The cooked parts are the elements of strings. The raw parts are in strings.raw.
function show(strings) {
return { cooked: strings[0], raw: strings.raw[0] };
}
const result = show`a\nb`;
console.log(result.cooked.length); // 3: 'a', newline, 'b'
console.log(result.raw.length); // 4: 'a', '\', 'n', 'b'Use the raw form when the backslashes carry meaning of their own, as in regular expressions, Windows paths, or LaTeX.
String.raw: The Built-In Tag
String.raw joins the raw parts and the values back together. You can also call it as a normal function by passing an object that has a raw array.
console.log(String.raw`C:\temp\new`); // C:\temp\new
console.log(String.raw({ raw: ['a', 'b', 'c'] }, 1, 2)); // a1b2cA common mistake is to expect String.raw to leave the values unprocessed as well. The values are already evaluated before the tag runs. Only the static text stays raw.
Tags Can Return Anything
A tag is an ordinary function, so it can return an object, an array, or another function. It does not have to return a string.
function parts(strings, ...values) {
return { count: values.length, values };
}
console.log(parts`x=${1}, y=${2}`); // { count: 2, values: [ 1, 2 ] }Practical Pattern: An Auto-Escaping HTML Tag
The static parts were written by you, so the tag can trust them. The values may come from users, so the tag escapes them. When reduce is called without an initial value, it starts from strings[0], and values[i - 1] is the value that sits just before strings[i].
const escapeHTML = (value) => String(value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
function html(strings, ...values) {
return strings.reduce((out, str, i) => out + escapeHTML(values[i - 1]) + str);
}
const user = '<img src=x onerror=alert(1)>';
console.log(html`<p>Hello, ${user}!</p>`);
// <p>Hello, <img src=x onerror=alert(1)>!</p>Exercise
What do String.raw\d+\.\d+` and the untagged template \d+\.\d+ ` each produce?
Show answer
String.raw returns \d+\.\d+ with the backslashes kept, so it works as a regex source. In the untagged template, \d and \. are unnecessary escapes that cook to d and ., so the result is d+.d+.