Sub topic 8
Raw Strings and String.raw
This chapter assumes you already know how a tag function receives its strings array and its values, as covered in the chapter on tagged templates. It also assumes you are comfortable with escape sequences such as \n and \t in ordinary string literals.
Every string part of a template literal exists in two forms. The cooked form is the string after escape sequences are interpreted, so \n becomes a newline character. The raw form is the exact source text between the backticks, so \n stays as two characters: a backslash and the letter n. Plain template literals only give you the cooked form. Tag functions can read both.
Cooked and Raw Side by Side
The strings array that a tag function receives has a raw property. strings.raw is a second array with the same length as strings, and it holds the uninterpreted text of each part.
function compare(strings) {
return {
cookedLength: strings[0].length,
rawLength: strings.raw[0].length,
raw: strings.raw[0]
};
}
console.log(compare`a\tb`);
// { cookedLength: 3, rawLength: 4, raw: 'a\\tb' }The cooked string has three characters (a, a tab, b). The raw string has four (a, \, t, b). Node prints the backslash doubled because it shows the string as a literal, but only one backslash is actually in it.
String.raw: The Built-in Raw Tag
String.raw is a tag function that ships with JavaScript. It joins the raw string parts with the substitution values and returns the result. Escape sequences are left alone, and substitutions are still evaluated as usual.
const dir = "reports";
console.log(String.raw`C:\new\${dir}\table`);
// C:\new\${dir}\table
console.log(String.raw`C:\new\${"x"}`.length);
// 10
const folder = "data";
console.log(String.raw`C:\${folder}`);
// C:\${folder}The ${ sequence needs care here. In the source, \${ is an escape that blocks substitution, and in the raw text the backslash is kept. So String.raw gives you a literal \${dir}, not the folder name. To put a value right after a backslash, end the literal part before the ${, using a separate template or concatenation:
const folder = "data";
console.log(String.raw`C:\new\ ` .trim() + folder);
// C:\new\data
console.log(String.raw`C:\new` + "\\" + folder);
// C:\new\dataWhen the backslash isn't directly before ${, substitution works normally:
const n = 2;
console.log(String.raw`a\n${n + 1}b`);
// a\n3bCommon uses
| Use | Example | Why raw helps |
|---|---|---|
| Windows paths | ``String.raw`C:\Users\ada` `` | No doubled backslashes |
| Regular expressions | ``new RegExp(String.raw`\d+\.\d+`)`` | Regex escapes pass through unchanged |
| Showing escape codes in docs | ``String.raw`Use \n for newline` `` | The text appears exactly as typed |
const version = new RegExp(String.raw`^\d+\.\d+\.\d+$`);
console.log(version.test("1.20.3")); // true
console.log(version.test("1x20x3")); // falseWritten as a normal string, the same pattern would be "^\\d+\\.\\d+\\.\\d+$", which is harder to read and easy to get wrong.
Calling String.raw as a Function
String.raw is an ordinary function, so you can call it without template syntax. Pass an object with a raw property, then the values to insert between its parts.
console.log(String.raw({ raw: ["a", "b", "c"] }, 1, 2));
// a1b2c
console.log(String.raw({ raw: "abc" }, "-", "-"));
// a-b-cIn the second call, the string "abc" is treated as an array-like of single characters, which makes String.raw a quick way to interleave a separator between characters. Extra values beyond the gaps are ignored. Missing values become empty strings.
Gotchas
- An escaped backtick keeps its backslash: `
String.raw\`yields the two characters\``. - Line endings are normalized in both forms. A CRLF line break in the source file appears as a single
\nin the cooked and the raw strings. String.rawonly affects the literal parts. It does not escape or alter the values you interpolate.
Exercise
What does this code print, and why? const t = "tab"; console.log(String.rawx\t${t}\ty.length);
Show answer
It prints 11. The raw parts are "x\t" (3 characters: x, backslash, t) and "\ty" (3 characters). The substitution inserts "tab" (3 characters) between them, giving x\ttab\ty, which is 3 + 3 + 3 = 9... recount: "x\t" is 3, "tab" is 3, "\ty" is 3, total 9. So it prints 9, because String.raw keeps each \t as two characters and inserts the evaluated value of t unchanged.
Exercise
Write a call to String.raw without template syntax that returns "1+2+3" from the values 1, 2, and 3.
Show answer
String.raw({ raw: ["", "+", "+", ""] }, 1, 2, 3). The raw array needs one more element than the number of values, so empty strings at both ends place the numbers at the start and end.