Sub topic 6
String.raw: The Built-In Tag
This chapter assumes you already know how a tag function receives a strings array and substitution values. It also assumes you know that each strings array has a raw property that holds the source text as written, with escapes left unprocessed. Here we look at the one tag that ships with the language, String.raw. You will see what it does, how it works when called as a plain function, where it helps, and where it trips people up.
What String.raw Does
String.raw is a tag function that joins the raw string parts with the substitution values. Escape sequences such as \n stay as a backslash followed by a letter, while ${} substitutions are still evaluated and inserted.
const cooked = `Line one\nLine two`;
const raw = String.raw`Line one\nLine two`;
console.log(cooked.length); // 17 (\n became one newline character)
console.log(raw.length); // 18 (\n stayed as two characters: \ and n)
console.log(raw); // Line one\nLine two
const dir = 'logs';
console.log(String.raw`C:\data\${dir}`); // C:\data\${dir} (see the pitfalls section)
console.log(String.raw`C:\data\ ${dir}`); // C:\data\ logsThe last two lines hint at a gotcha covered later in this chapter. Escapes are skipped, but substitution syntax still has rules.
The Signature: Calling It Without a Template
String.raw is an ordinary function with this signature:
String.raw(callSite, ...substitutions)When you use it as a tag, JavaScript passes the strings array as callSite. String.raw reads only callSite.raw. It never looks at the cooked strings. So you can call it directly with any object that has a raw property:
console.log(String.raw({ raw: ['a', 'b', 'c'] }, 1, 2)); // 'a1b2c'
console.log(String.raw({ raw: ['x', 'y'] }, 1, 2, 3)); // 'x1y' (extra values ignored)
console.log(String.raw({ raw: ['a', 'b', 'c'] }, 1)); // 'a1bc' (missing values become '')
console.log(String.raw({ raw: [] }, 1, 2)); // '' (no parts, empty result)
console.log(String.raw({ raw: 'test' }, 0, 1, 2)); // 't0e1s2t'The last line looks odd, but it follows from the rules. raw only needs to be array-like, meaning it has a length and indexed elements. A string fits that, so 'test' acts like ['t', 'e', 's', 't'].
The algorithm
The specification describes a short loop. In words:
- Read
callSite.rawand itslength. If the length is 0 or less, return''. - Append raw part 0.
- For each later raw part
i, first append substitutioni - 1if one was passed, then append raw parti. - Stop after the last raw part. Any leftover substitutions are never read.
The number of raw parts controls the output. That is why extra values disappear and why missing values leave the gaps empty.
Writing it yourself
Rebuilding String.raw is a good check that you understand it:
function myRaw(callSite, ...subs) {
const raw = Object(callSite.raw);
const len = Math.max(0, Math.floor(Number(raw.length)) || 0);
if (len === 0) return '';
let out = `${raw[0]}`;
for (let i = 1; i < len; i++) {
if (i - 1 < subs.length) out += `${subs[i - 1]}`;
out += `${raw[i]}`;
}
return out;
}
console.log(myRaw`a\nb${1}c`); // a\nb1c
console.log(myRaw({ raw: 'test' }, 0, 1, 2)); // t0e1s2t
console.log(myRaw({ raw: ['a', 'b', 'c'] }, 1)); // a1bc
console.log(myRaw({ raw: ['a', 'b'] }, undefined)); // aundefinedbThe code converts values with ` ${x} instead of String(x) on purpose. The built-in uses the spec's ToString operation, which throws a TypeError for Symbols. String(Symbol()) would quietly return 'Symbol()'`, which is a different behavior.
The last call shows a fine distinction. A substitution that is missing adds nothing. A substitution that is passed as undefined adds the text 'undefined'.
Where String.raw Helps
Windows paths
const path = String.raw`C:\Users\ada\new_folder\x64`;
console.log(path); // C:\Users\ada\new_folder\x64In an untagged template, \n would become a newline. \x64 would become the letter d, and \U would just lose its backslash. With String.raw, every backslash stays.
Regular expression sources
The RegExp constructor takes a string. Normally every backslash must be doubled, as in '\\d+\\.\\d+'. String.raw lets you write the pattern as it would look in a regex literal:
const version = new RegExp(String.raw`^(\d+)\.(\d+)\.(\d+)$`);
console.log(version.test('1.24.3')); // true
const word = 'cat';
const wholeWord = new RegExp(String.raw`\b${word}\b`, 'g');
console.log('cat concat cat'.match(wholeWord)); // [ 'cat', 'cat' ]LaTeX, shell snippets, and other backslash-heavy text
const formula = String.raw`\frac{1}{2} + \sqrt{x}`;
console.log(formula); // \frac{1}{2} + \sqrt{x}Without the tag, \f would become a form-feed character and \s would lose its backslash.
Using String.raw Inside Your Own Tags
String.raw reads .raw, so you can pass any array in that slot. Passing the cooked strings array gives you a one-line default reassembly:
function passthrough(strings, ...values) {
return String.raw({ raw: strings }, ...values);
}
console.log(passthrough`tab:\there ${42}`); // 'tab:<TAB>here 42' with a real tabThis rebuilds the same string an untagged template would produce. That makes it a handy base when your tag only needs to change the values:
function upperValues(strings, ...values) {
return String.raw({ raw: strings }, ...values.map((v) => String(v).toUpperCase()));
}
console.log(upperValues`hello ${'world'}\n`); // 'hello WORLD' followed by a real newlineOne edge case: if a cooked part is undefined because of an invalid escape, this trick inserts the text 'undefined'. A later chapter explains when cooked parts become undefined.
Pitfalls
Each case below is easy to get wrong, so check them against the comments.
// 1. A backslash before a backtick escapes it, and the backslash stays in raw.
console.log(String.raw`a\`b`); // a\`b
// 2. A backslash before ${ blocks the substitution entirely.
const x = 5;
console.log(String.raw`\${x}`); // \${x}
// 3. Unicode and hex escapes are not decoded.
console.log(String.raw`\u0041\x41`); // \u0041\x41 (not 'AA')
// 4. Two backslashes stay two backslashes.
console.log(String.raw`\\`.length); // 2Two more rules can't be shown as runnable lines:
- A template can't end with an odd number of backslashes. `
String.rawC:\is a syntax error. The\`escapes the closing backtick, so the literal never ends. UseString.rawC:\\, but note that it produces two backslashes. To get one trailing backslash, writeString.rawC:+ '\\'orString.rawC:${'\\'}`. - Line endings are normalized even in raw text. If your source file uses CRLF (
\r\n) line endings, a multiline raw string still contains only\n. Raw mode keeps escape sequences as written, but it does not keep literal carriage returns.
| Source text | `String.raw` result | Untagged template result |
|---|---|---|
| `` `a\nb` `` | `a\nb` (4 characters) | `a`, newline, `b` (3 characters) |
| `` `\u0041` `` | `\u0041` | `A` |
| `` `\unicode` `` | `\unicode` | SyntaxError |
| `` `\${x}` `` | `\${x}` | `${x}` |
| `` `\\` `` | `\\` (2 characters) | `\` (1 character) |
Exercise
Without running it, predict the output of String.raw({ raw: ['<', '|', '>'] }, 'a', 'b', 'c', 'd') and String.raw({ raw: 'ab' }, undefined).
Show answer
The first gives '<a|b>'. There are three raw parts, so only two substitutions are used, and 'c' and 'd' are ignored. The second gives 'aundefinedb'. The string 'ab' acts as the parts ['a', 'b'], and undefined was passed explicitly, so it is converted to the text 'undefined'.
Exercise
A teammate writes const re = new RegExp(String.raw^${ext}\d+$) with ext = '.log'. Why does re.test('xlog12') return true, and how should it be fixed?
Show answer
String.raw inserts '.log' unchanged, so the pattern becomes ^.log\d+$. The unescaped dot matches any character, including 'x'. Escape the value for regex syntax before inserting it, for example ext.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), which gives ^\.log\d+$.
Exercise
Write a tag named dedentRaw that behaves like String.raw but removes one leading newline if the result starts with one. Use String.raw internally.
Show answer
function dedentRaw(strings, ...values) { const s = String.raw(strings, ...values); return s.startsWith('\n') ? s.slice(1) : s; } This works because the leading newline in a multiline template is a real line break in the source, so it appears as an actual newline character in the raw text. A typed \n escape would not count, because it stays as a backslash and the letter n.