Sub topic 8
Raw Strings and String.raw
Every template literal has two versions of its literal text. The cooked version is the one you normally see: escape sequences such as \n and \t have already been turned into the characters they stand for. The raw version is the source text exactly as you typed it, with backslashes kept. This chapter shows how to read the raw version from a tag function, how the built-in String.raw tag uses it, and where that helps or causes surprises.
This chapter assumes you have read the previous chapter on tagged templates. You should know that a tag function receives a strings array and the substitution values as separate arguments. You should also be comfortable with reduce and rest parameters.
Cooked and Raw Text
When the JavaScript engine parses a template literal, it splits the literal text into segments around each ${...} substitution. It then produces two strings for each segment:
- The cooked string has every escape sequence interpreted.
\nbecomes a newline character,\u0041becomesA, and\\becomes a single backslash. - The raw string keeps the characters from the source code.
\nstays as two characters, a backslash and the lettern.
An untagged template literal only ever produces the cooked text. A tagged template gives the tag function both: the cooked strings are the elements of the strings array, and the raw strings are in strings.raw.
Here is a tag that returns both versions of the first segment so you can compare them:
function show(strings) {
return { cooked: strings[0], raw: strings.raw[0] };
}
const r = show`a\tb`;
console.log(r.cooked.length); // 3
console.log(r.raw.length); // 4
console.log(JSON.stringify(r)); // {"cooked":"a\tb","raw":"a\\tb"}The cooked string has three characters: a, a tab, and b. The raw string has four: a, a backslash, t, and b. JSON.stringify makes the difference visible because it escapes the backslash in the raw string.
The strings.raw array always has the same length as strings, and its indexes line up: strings.raw[i] is the source form of strings[i]. Like the strings array, the raw array is frozen, so a tag cannot change it.
How Common Sequences Compare
| Source text | Cooked value | Cooked length | Raw value | Raw length |
|---|---|---|---|---|
| `\n` | newline character | 1 | backslash, n | 2 |
| `\t` | tab character | 1 | backslash, t | 2 |
| `\u0041` | A | 1 | backslash, u, 0, 0, 4, 1 | 6 |
| `\\` | one backslash | 1 | two backslashes | 2 |
| `\w` | w | 1 | backslash, w | 2 |
| backslash then a line break | empty (line continuation) | 0 | backslash, newline | 2 |
The \w row matters more than it looks. In a normal string, a backslash before a character that has no escape meaning just disappears, so "\w" is "w". That silent loss is the usual reason regular expressions built from ordinary strings break.
Line Continuations and Line Endings
A backslash at the end of a line is a line continuation. In cooked text it produces nothing, so the two lines join. In raw text it stays as a backslash followed by a newline:
const cooked = `\u0041 a\
b`;
const raw = String.raw`\u0041 a\
b`;
console.log(cooked); // A ab
console.log(JSON.stringify(raw)); // "\\u0041 a\\\nb"One normalization does apply to raw text. If your file uses Windows line endings (carriage return plus line feed) or lone carriage returns, the engine converts each line ending inside a template to a single line feed (\n) in both the cooked and the raw strings. So raw text is the source text with backslashes kept, except that line endings are normalized. This keeps template output the same whatever line-ending setting an editor or Git checkout uses.
String.raw as a Tag
String.raw is a built-in tag function. It joins the raw segments with the substitution values and returns the result. Escape sequences in the literal text are left alone, while ${...} substitutions are still evaluated and inserted.
console.log(String.raw`C:\new\table`); // C:\new\table
console.log("C:\new\table");
// C:
// ew ableThe second line shows the problem String.raw solves. In the ordinary string, \n becomes a newline and \t becomes a tab, which ruins the path.
Substitutions work as usual:
const count = 2 + 1;
console.log(String.raw`\n is not a newline, and count is ${count}`);
// \n is not a newline, and count is 3String.raw converts each substitution value with string conversion, the same rule plain interpolation uses. An object with both toString and valueOf therefore shows its toString result, as you saw in the chapter on string conversion.
Regular Expressions Without Double Escaping
The most common practical use is writing regular expression sources for the RegExp constructor. With ordinary strings, every backslash in the pattern has to be doubled:
const doubled = new RegExp("^v(\\d+)\\.(\\d+)\\.(\\d+)$");
const viaRaw = new RegExp(String.raw`^v(\d+)\.(\d+)\.(\d+)$`);
console.log(doubled.source === viaRaw.source); // true
console.log(viaRaw.exec("v1.20.3").slice(1)); // [ '1', '20', '3' ]The raw version reads the same as a regex literal, which makes it easier to copy patterns between a regex literal and dynamic code. Other uses include Windows paths, LaTeX source, and any text where backslashes are content rather than escapes.
Gotchas with String.raw
Raw does not mean "anything goes". The parser still has to find where the template ends and where each substitution starts, and a backslash still affects that. These cases surprise people.
A Backslash Before `${` Disables the Substitution
\$ is a valid escape in a template, and it stops ${ from starting a substitution. In a raw string the backslash also stays. So a path segment that follows a backslash does not get interpolated:
const dir = "Users";
console.log(String.raw`C:\${dir}`); // C:\${dir}
console.log(String.raw`C:\\${dir}`); // C:\\Users
console.log(String.raw`C:${"\\"}${dir}`); // C:\UsersThe first line prints the literal text ${dir}. The second line does interpolate, but the raw text keeps both backslashes. The third line gives the intended result by inserting the backslash as a substitution value. Building the path with path.win32.join or an array join("\\") is often clearer.
A Trailing Backslash Is a Syntax Error
` String.rawC:\ does not parse. The backslash escapes the closing backtick, so the template never ends and the engine reports a syntax error. Put the trailing backslash in a substitution ( String.rawC:${"\\"} ) or use an ordinary string such as "C:\\"`.
Escaped Backticks Keep Their Backslash
You can put a backtick inside a raw template by escaping it, but the backslash stays in the output:
console.log(String.raw`a\`b`); // a\`b
console.log(String.raw`a\`b`.length); // 4If you need a bare backtick, insert it as a value: ` String.rawa${""}b ` gives a backtick between a and b` with no backslash.
Malformed Escapes
Some sequences, such as \u followed by something other than hex digits, are not valid escapes. In an untagged template they are a syntax error. In a tagged template they are allowed: the cooked segment becomes undefined and the raw segment still holds the text, so String.raw handles them fine. The last chapter of this tutorial covers that rule in detail.
Calling String.raw as a Plain Function
String.raw does not need a real template. It accepts any object with a raw property that is array-like, followed by the substitution values. It reads raw.length segments and puts one value between each pair:
console.log(String.raw({ raw: ["x", "y", "z"] }, 1, 2, 3)); // x1y2z
console.log(String.raw({ raw: ["a", "b", "c"] }, 1)); // a1bc
console.log(String.raw({ raw: "abc" }, "-", "+")); // a-b+c
console.log(JSON.stringify(String.raw({ raw: [] }, 1))); // ""The rules these lines show:
- Values beyond
raw.length - 1are ignored, so the3in the first line never appears. - Missing values are treated as empty strings, which is why the second line ends in
bc. - A string is array-like, so
{ raw: "abc" }treats each character as a segment. This is a short way to put a separator between characters. - An empty
rawarray returns an empty string.
Calling String.raw directly is rare in application code. It is useful when a custom tag wants to delegate the final join: return String.raw({ raw: strings.raw }, ...processedValues);. You can also pass the whole strings array as the first argument, because it already has a raw property.
Using strings.raw in Your Own Tags
Any tag can choose raw segments instead of cooked ones. A tag that builds regular expressions is a good example, because cooked text would quietly drop backslashes. This tag keeps the literal pattern raw and escapes every interpolated value so it matches literally:
function re(strings, ...values) {
const escapeRe = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const source = strings.raw.reduce(
(out, str, i) => out + escapeRe(values[i - 1]) + str
);
return new RegExp(source);
}
const ext = "c++";
const pattern = re`^\w+\.${ext}$`;
console.log(pattern.source); // ^\w+\.c\+\+$
console.log(pattern.test("main.c++")); // true
console.log(pattern.test("main.cxx")); // falseThe tag calls reduce with no initial value, so the accumulator starts as strings.raw[0] and the index starts at 1. That is why the value for each step is values[i - 1].
Compare what the cooked strings would have given. The first cooked segment of ` re^\w+\.${ext}$ is "^w+.". The \w lost its backslash and became the letter w, and \. became an unescaped dot that matches any character. Reading strings.raw` is the whole fix.
When you write your own raw-based tag, convert values with String(value) or a template (` ${value} ) rather than out + value. The + operator uses the default conversion hint and can call valueOf, which would make your tag behave differently from String.raw` and plain interpolation.
Choosing Cooked or Raw in a Tag
| Situation | Use | Reason |
|---|---|---|
| Building normal text, HTML, or messages | `strings` (cooked) | Authors expect `\n` to be a newline |
| Building regex sources, paths, or LaTeX | `strings.raw` | Backslashes are content |
| Writing a small domain-specific language with its own escapes | `strings.raw` | The tag interprets escapes itself |
| Accepting text that may contain malformed escapes | `strings.raw` | Cooked segments can be `undefined` |
Exercises
Exercise
What do String.rawa\nb.length and ` a\nb.length ` return, and why do they differ?
Show answer
The raw version returns 4 because it keeps the backslash and the letter n as two separate characters. The cooked version returns 3 because \n becomes a single newline character.
Exercise
A developer writes ` const p = String.rawD:\${folder}\logs; with folder set to "app" and gets the text D:\${folder}\logs. Explain what happened and give a fix that produces D:\app\logs`.
Show answer
The backslash before ${ escapes the dollar sign, so the parser treats ${folder} as literal text and no substitution happens. String.raw keeps that backslash too. One fix is ` String.rawD:${"\\"}${folder}\logs , which inserts the backslash as a value. Another is ["D:", folder, "logs"].join("\\")`.
Exercise
What does String.raw({ raw: ["<", ">"] }, "x", "y") return?
Show answer
It returns "<x>". The raw array has two segments, so String.raw uses only one value between them. The extra value "y" is ignored.
Exercise
Write a tag rawUpper that returns the raw literal text unchanged but inserts every substitution value in upper case. For example, ` rawUpperC:\temp\${"logs"} would keep the backslash before the substitution as written, and rawUpper\t${"ab"}\n ` should return the six-character string backslash, t, AB, backslash, n.
Show answer
function rawUpper(strings, ...values) { return String.raw({ raw: strings.raw }, ...values.map(v => String(v).toUpperCase())); } This passes the raw segments to String.raw and converts each value with String before upper-casing it, so the literal backslashes are kept and only the values change.