Sub topic 4
Escaping Backticks and Dollar-Brace Sequences
A template literal gives three character sequences special meaning. A backtick ends the literal. The pair ${ starts a substitution. A backslash starts an escape sequence. When you need any of these to show up as plain text, you have to escape it. This chapter explains the escaping rules, the shortcuts that work, the mistakes that cause syntax errors or silently wrong strings, and how to escape text correctly when you generate template literal source code.
This chapter assumes you already know:
- how regular single- and double-quoted strings handle escapes such as
\nand\" - the backtick syntax and
${}interpolation covered in the earlier chapters - basic regular expressions and
String.prototype.replace
How the Parser Reads a Template Literal
To see why escaping works the way it does, follow how the JavaScript lexer scans the inside of a template literal. It reads one character at a time and checks only a few cases. Everything else is literal text.
The diagram shows three things:
- A
$is special only when the character right after it is{. A lone$is ordinary text. - A
{or}on its own is ordinary text. Braces only matter after a${has opened a substitution. - The backslash is checked before anything else can match, so
\followed by a backtick or by$stops those characters from being treated as special.
Escaping a Backtick
To put a backtick inside a template literal, write ` \ ``:
console.log(`Use \`backticks\` and \${not interpolated}`);
// Use `backticks` and ${not interpolated}Single and double quotes need no escaping inside backticks. That is one reason template literals are convenient for text that contains both kinds of quote:
console.log(`It's "fine" to mix quotes here.`);
// It's "fine" to mix quotes here.It also works the other way. A regular quoted string can hold a backtick without any escape:
console.log("Wrap code in `backticks`.");
// Wrap code in `backticks`.Escaping the Dollar-Brace Sequence
To write the two characters ${ literally, escape either character. All three forms below give the same result:
console.log(`\${name}`); // ${name}
console.log(`$\{name}`); // ${name}
console.log(`\$\{name}`); // ${name}The first form, \${, is the usual one and the easiest to read. The second form works because \{ is a "non-escape character" escape: a backslash before a character that has no special escape meaning just produces that character. So \{ becomes {, and since the lexer saw $ followed by a backslash, it never started a substitution.
The closing brace never needs escaping. Once no substitution is open, } is plain text.
When No Escape Is Needed
Because $ matters only right before {, many dollar signs are already safe:
const price = 5;
console.log(`$5 and $ {x} and {braces} and $`);
// $5 and $ {x} and {braces} and $
console.log(`Total: $${price}`);
// Total: $5The second line matters for currency formatting. In $${price}, the first $ is followed by another $, not by {, so it is literal. The second $ begins the substitution.
Producing Special Characters from a Substitution
Escaping is not the only way to get a backtick or ${ into the output. A substitution can return any string, and the code inside ${} follows ordinary JavaScript rules. A string literal inside a substitution uses its own quoting rules:
console.log(`${"`"} and ${"${"}`);
// ` and ${The lexer does not close the outer template at the backtick inside "". While parsing the substitution it is in expression mode, so it reads "" as a complete double-quoted string. In the same way, a backtick that appears directly inside ${} starts a nested template literal instead of ending the outer one. The nesting chapter covers that case.
This approach is rarely clearer than ` \ ` or \${. It is useful when the special text comes from a variable or constant, such as a code generator that keeps const OPEN = "${";` in one place.
The Other Escape Sequences
Template literals support the same escape sequences as regular strings, with a few stricter rules. The table lists the ones you are likely to meet.
| Source in template | Resulting string | Notes |
|---|---|---|
| `` \` `` | `` ` `` | Literal backtick |
| `\${` or `$\{` | `${` | Literal dollar-brace |
| `\\` | `\` | Literal backslash |
| `\n`, `\t`, `\r` | newline, tab, carriage return | Same as regular strings |
| `\x41` | `A` | Exactly two hex digits |
| `\u0041`, `\u{1F600}` | `A`, 😀 | Four hex digits, or 1 to 6 in braces, max `10FFFF` |
| `\0` | NUL character | Allowed only if no digit follows |
| `\` + newline | nothing | Line continuation, the newline is removed |
| `\d`, `\q`, `\{` | `d`, `q`, `{` | Backslash is dropped |
| `\01`, `\1` to `\9` | SyntaxError | Legacy octal and `\8`, `\9` are banned |
| `\xZ`, `\u{110000}` | SyntaxError | Malformed hex or out-of-range code point |
Banned Escapes Are Syntax Errors
Regular strings in sloppy mode still accept legacy octal escapes such as "\101". Template literals never do, even outside strict mode. Malformed \x and \u escapes are also errors. A syntax error stops the whole script from parsing, so the demo below wraps each example in eval to catch the error:
const samples = ["`\\0`", "`\\01`", "`\\1`", "`\\xZ`", "`\\u{110000}`"];
for (const src of samples) {
try {
const value = eval(src);
console.log(src, "->", JSON.stringify(value));
} catch (e) {
console.log(src, "->", e.name);
}
}
// `\0` -> "\u0000"
// `\01` -> SyntaxError
// `\1` -> SyntaxError
// `\xZ` -> SyntaxError
// `\u{110000}` -> SyntaxErrorTagged templates relax this rule: an invalid escape there gives an undefined cooked string instead of an error. A later chapter covers that case.
Line Continuation
A backslash at the very end of a line removes the line break. You can split a long string across source lines without the break ending up in the value:
const s = `first part, \
second part`;
console.log(s); // first part, second partAny indentation on the second source line would still be included, because only the backslash and the newline are removed.
Gotchas
A Trailing Backslash Swallows the Closing Backtick
If a template ends with a single backslash, that backslash escapes the closing backtick. The literal then never ends, and you get a syntax error such as "Unterminated template literal". To end a string with a backslash, double it:
const dir = `C:\\Users\\`;
console.log(dir); // C:\Users\Unknown Escapes Fail Silently
The most common real bug is a backslash that should have been kept but was dropped. Regular expression source is the usual example. \d is not a string escape, so the template turns it into a plain d:
const wrong = new RegExp(`\d+`);
const right = new RegExp(`\\d+`);
console.log(wrong.source); // d+
console.log(right.source); // \d+
console.log(wrong.test("123")); // false
console.log(right.test("123")); // trueNo error appears. The pattern just matches the wrong text. The same problem hits Windows paths: in a template, \t becomes a tab and \n becomes a newline, so a path like C:\temp\new is corrupted. Either double every backslash or use String.raw, which a later chapter covers.
Line Endings Are Normalized
A carriage return typed directly in the source, whether a lone CR or a CRLF pair, becomes a single LF in the template's value. A file saved with Windows line endings therefore still produces \n in multiline templates. If you really need a carriage return in the value, write the escape \r explicitly.
Escaping Text When Generating Code
Code generators, build tools, and snippet editors sometimes take arbitrary text and emit it as a template literal in generated JavaScript. To do that safely, escape every character that would change meaning:
- every backslash, so existing backslashes are kept
- every backtick, so the literal does not end early
- every
${, so no substitution starts - every carriage return, so line-ending normalization does not change the text
A single regular expression with alternatives handles all four. Because the escapes are added in one pass, a backslash added for one match is never escaped a second time.
function toTemplateSource(text) {
const escaped = text.replace(/\\|`|\$\{|\r/g, (m) =>
m === "\r" ? "\\r" : "\\" + m
);
return "`" + escaped + "`";
}
const original = "Price: ${amount}, code: `x`, path: C:\\temp\r\nend";
const source = toTemplateSource(original);
console.log(source);
// `Price: \${amount}, code: \`x\`, path: C:\\temp\r
// end`
console.log(eval(source) === original); // trueThe round trip through eval shows the escaping is complete: the generated literal evaluates back to exactly the original text. The literal newline stays as a real line break in the generated source. That is legal in a template, and only the carriage return before it needed an escape.
Two mistakes are common here. Escaping only backticks leaves ${ live, so the generated code runs a substitution, which is a code injection bug if the text came from a user. Escaping backticks and ${ without escaping backslashes first changes any text that already contains backslashes, and text that ends in a backslash breaks the generated code.
Templates That Write Templates
When you write generated code directly as a template, the inner template's delimiters and substitutions must be escaped in the outer one:
const fn = "greet";
const code = `function ${fn}(name) {
return \`Hello, \${name}!\`;
}`;
console.log(code);
// function greet(name) {
// return `Hello, ${name}!`;
// }Here ${fn} is interpolated now, when the generator runs. The escaped \${name} is left as text for the generated function to interpolate later. Reading the source becomes harder each time you add another level, so for deep code generation it is usually clearer to build the output from smaller pieces.
Choosing an Approach
| Situation | Recommended form |
|---|---|
| One literal backtick or `${` in handwritten text | `` \` `` and `\${` |
| Dollar amounts before an interpolation | `$${value}`, no escape needed |
| Backslash-heavy text such as regex or paths | `\\` everywhere, or `String.raw` |
| Special text stored in a constant | Interpolate it: `${OPEN}` |
| Arbitrary text emitted as template source | A single-pass escaper like `toTemplateSource` |
Exercise
What does each line print? (a) console.log($${2 + 3}); (b) console.log(\${2 + 3}); (c) console.log($\{2 + 3}); (d) console.log({${2 + 3}});
Show answer
(a) $5, because the first $ is followed by $ and is literal. (b) ${2 + 3}, because the escaped $ cannot start a substitution. (c) ${2 + 3}, because \{ becomes { and the lexer saw $ followed by a backslash, not by {. (d) {5}, because braces outside a substitution are ordinary text.
Exercise
A teammate writes const re = new RegExp(^\w+\.js$); to match file names like "app.js". Why does it fail, and how do you fix it?
Show answer
\w and \. are not string escapes, so the template drops the backslashes and the pattern becomes ^w+.js$, which matches "wwwXjs" but not "app.js". Write ^\\w+\\.js$ (or use String.raw) so that the regex receives the backslashes.
Exercise
An escaper is written as text.replace(//g, "\\").replace(/\$\{/g, "\\${"). Give an input for which the generated template literal does not evaluate back to the original text, and explain why.
Show answer
The input "a\" (a followed by one backslash) produces the source a\, where the backslash escapes the closing backtick and causes a SyntaxError. Input containing "\n" as two characters becomes a real newline after evaluation. The escaper must also escape backslashes, all in one pass, for example text.replace(/\\|`|\$\{/g, m => "\\" + m).
Exercise
Which of these is a SyntaxError in an untagged template literal: \0, \07, \8, \x4, \q?
Show answer
\07, \8, and \x4 are SyntaxErrors: \0 followed by a digit is a banned legacy octal escape, \8 and \9 are not allowed in templates, and \x needs exactly two hex digits. \0 is the NUL character, and \q silently becomes "q".