Sub topic 5
Cooked and Raw Strings
This chapter assumes you know how a tag function receives a strings array and a list of values (covered in the previous chapters). You should also be comfortable with escape sequences such as \n, \t, and \u0041, and with Array.prototype.reduce.
Every static part of a tagged template exists in two forms. The cooked form is the string after JavaScript has processed escape sequences, so it is what an untagged template would produce. The raw form is the text exactly as you typed it in the source file, with backslashes kept. The tag function sees the cooked forms as the elements of strings and the raw forms in strings.raw.
Where the Raw Strings Live
The first argument to a tag is an array of cooked strings. That array also carries a property called raw, which is a second array of the same length holding the raw strings. The two arrays line up index by index: strings[i] and strings.raw[i] describe the same piece of source text.
function parts(strings) {
return strings.map((cooked, i) => ({
cooked,
raw: strings.raw[i],
cookedLength: cooked.length,
rawLength: strings.raw[i].length,
}));
}
console.log(parts`Tab:\t|A:\u0041`);
// [ { cooked: 'Tab:\t|A:A', raw: 'Tab:\\t|A:\\u0041', cookedLength: 8, rawLength: 15 } ]The template has no substitutions, so there is a single part. In the cooked string, \t became one tab character and \u0041 became the letter A. In the raw string, both escape sequences stay as the literal characters you wrote: a backslash followed by t, and a backslash followed by u0041.
The processing is easier to follow as a diagram:
How Each Escape Looks in Both Forms
Use the table below to predict what a tag will see. The "Raw characters" column lists the actual characters stored, with no extra escaping.
| Source text | Cooked result | Cooked length | Raw characters | Raw length |
|---|---|---|---|---|
| `\n` | newline | 1 | backslash, `n` | 2 |
| `\t` | tab | 1 | backslash, `t` | 2 |
| `\u0041` | `A` | 1 | backslash, `u0041` | 6 |
| `\x41` | `A` | 1 | backslash, `x41` | 4 |
| `\\` | one backslash | 1 | two backslashes | 2 |
| `` \` `` | backtick | 1 | backslash, backtick | 2 |
| `\${` | `${` | 2 | backslash, `${` | 3 |
| backslash at end of line | nothing (line continuation) | 0 | backslash, newline | 2 |
| a CRLF line break | newline | 1 | newline | 1 |
Some rows are easy to get wrong.
- Escaped backticks and
\${keep their backslash in raw form. You need the backslash to stop the parser from ending the template or starting a substitution. The raw string records it anyway. - Line continuations disappear only from the cooked form. A backslash right before a line break joins the two lines in the cooked string. The raw string keeps both the backslash and the line break.
- Line endings are normalized in both forms. A file saved with Windows line endings (
\r\n) still gives a single\nin raw strings. Raw is "as written" for escape sequences only. It does not copy the file byte for byte.
You can check the line-continuation case yourself:
function both(strings) {
return [strings[0], strings.raw[0]];
}
const [cooked, raw] = both`a\
b`;
console.log(cooked, cooked.length); // ab 2
console.log(JSON.stringify(raw), raw.length); // "a\\\nb" 4The raw string has four characters: a, a backslash, a newline, and b.
Raw Applies Only to the Static Parts
Raw and cooked describe the literal text between substitutions. The substitution values are already evaluated by the time the tag runs, so they have no raw form. A value that contains a backslash arrives as a plain string, and a value that is a number arrives as a number.
function inspect(strings, ...values) {
return { raw: strings.raw, values };
}
const path = 'C:\\new'; // a regular string literal: C, :, backslash, n, e, w
console.log(inspect`dir=${path}\n`);
// { raw: [ 'dir=', '\\n' ], values: [ 'C:\\new' ] }The raw array never includes the ${path} source text. It holds 'dir=' and the two characters \n that came after the substitution. Whatever escaping produced the value happened in the ordinary string literal 'C:\\new', before the template was evaluated.
The Raw Array Is Frozen Too
The strings array is frozen, and so is strings.raw. The raw property on strings is also non-writable and non-enumerable. Because it is non-enumerable, console.log(strings) in Node does not show it, and spreading [...strings] drops it.
function check(strings) {
return {
rawFrozen: Object.isFrozen(strings.raw),
rawEnumerable: Object.keys(strings).includes('raw'),
copyHasRaw: 'raw' in [...strings],
};
}
console.log(check`x`);
// { rawFrozen: true, rawEnumerable: false, copyHasRaw: false }This causes a common bug. If one tag passes [...strings] to another tag, the second tag loses access to the raw strings. Pass the original strings object along, or build a new object with a raw property yourself.
A Tag That Builds on Raw Strings
Raw strings are most useful when backslashes mean something to a later consumer, such as a regular expression engine, a Windows path, or LaTeX. The tag below builds a RegExp from the raw parts, so you write regex escapes once instead of doubling every backslash. It escapes the substituted values so they match literally.
const escapeRegExp = (value) =>
String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
function re(strings, ...values) {
const source = strings.raw.reduce(
(out, str, i) => out + escapeRegExp(values[i - 1]) + str,
);
return new RegExp(source);
}
const ext = 'tar.gz';
const pattern = re`^\w+\.${ext}$`;
console.log(pattern.source); // ^\w+\.tar\.gz$
console.log(pattern.test('backup.tar.gz')); // true
console.log(pattern.test('backup.tarXgz')); // falseWith cooked strings, this would fail. \w and \. are not valid string escapes, so an untagged template would turn them into plain w and .. The pattern would then mean "the letter w, one or more times, then any character". With strings.raw, the regex engine receives \w and \. unchanged.
The reduce call works the same way as in the interleaving chapter. With no initial value, out starts as strings.raw[0], i starts at 1, and values[i - 1] picks the value that sits before each later part.
Choosing Between Cooked and Raw
| You want | Use |
|---|---|
| The same text an untagged template would produce | `strings` (cooked) |
| Backslashes passed through to another language or format | `strings.raw` |
| Text that contains sequences JavaScript cannot parse as escapes | `strings.raw` (the cooked part is `undefined`) |
| Exact original bytes, including CRLF | Neither form gives you this |
The third row comes up in a later chapter. When a tagged template contains something like \unicode, which is not a valid escape, the cooked element is undefined but the raw element is still available. The next chapter covers String.raw, a built-in tag that joins the raw parts with the values, much like the re tag above does before calling new RegExp.
Common Errors
- Reading console output as the stored value.
'\\n'in a log is two characters. Check thelengthto confirm. - Assuming raw keeps everything. Line endings are still normalized, and substitution expressions are never included.
- Losing
rawby copying. Spreading,Array.from, andsliceall return plain arrays without therawproperty. - Mixing indexes.
strings.raw[i]andstrings[i]refer to the same part. Values usevalues[i - 1]when you interleave starting from part 0.
Exercise
For the call taga\tb${1}\c` , what are strings, strings.raw, and their lengths? Give each string's characters and length.
Show answer
There are two parts. strings is ['a<TAB>b', 'c'], with lengths 3 and 2. strings.raw is ['a\tb', '\c'] written as characters: a, backslash, t, b (length 4), and backslash, backtick, c (length 3). The value 1 appears in neither array.
Exercise
A colleague writes function lower(strings, ...values) { return otherTag([...strings], ...values); } and otherTag reads strings.raw. What goes wrong, and how do you fix it?
Show answer
Spreading creates a plain array without the non-enumerable raw property, so strings.raw is undefined inside otherTag and reading strings.raw[0] throws a TypeError. Pass the original object with otherTag(strings, ...values), or build a replacement that has a raw property, such as Object.assign([...strings], { raw: strings.raw }).
Exercise
Why does re^\d+$ built from strings.raw match '123', while new RegExp(^\d+$) built from an untagged template does not?
Show answer
In the untagged template, \d is not a recognized string escape, so the cooked text drops the backslash and the pattern becomes ^d+$, which matches only strings of the letter d. The raw string keeps the backslash, so the regex engine receives ^\d+$ and matches digits.