Write JavaScript string literals with correct escaping
How escaping in JavaScript string literals works, what it changes and what it leaves alone, and when to escape, use a template literal or keep plain characters.
Escaping a JavaScript string literal rewrites how text appears in source code so the parser reads it as you intended. It does not change the text itself. This review covers when escaping is the right choice, what it changes, and how escaped strings behave when copied, searched or shown to readers. It relies on documented language behavior. No particular escaping tool, editor or screen reader was tested for this article.
Is escaping the right transformation for your use?
Escaping is the right choice when text must sit inside JavaScript source code and contains characters that would end the literal early, break the line, or be hard to see. The main benefit is that it is lossless: a correctly escaped literal produces exactly the same string value at runtime as the original text. The main cost is readability in the source. Every backslash sequence is something a person has to decode mentally, and heavily escaped strings are harder to review and edit.
Plain characters are usually better when the source file is saved as UTF-8 and the text has no delimiter conflicts, backslashes, line breaks or invisible characters. Writing café directly is clearer than writing caf\u00e9, and both give the same value. Plain text is also better when the content is really data or user-facing copy, such as long paragraphs or translatable messages. That kind of content often belongs in a data or localization file rather than a hand-escaped literal.
Escaping a JavaScript literal is a different job from escaping text for HTML, JSON, SQL or a shell command. It also does not make untrusted input safe to splice into generated code. If the destination is not JavaScript source, use the escaping rules of that destination.
What escaping actually changes
Escaping changes the characters stored in your source file. It leaves the runtime string unchanged. This is not reversal, mirroring, a styled "font" or a display effect. No characters are reordered or swapped for look-alikes. The parser reads each escape sequence and produces the character it stands for.
The three literal forms
JavaScript has single-quoted, double-quoted and backtick (template) literals. Each form needs a different set of characters escaped. The three lines below produce the same string: an apostrophe, double quotes and a trailing newline.
const a = 'It\'s a "test"\n';
const b = "It's a \"test\"\n";
const c = `It's a "test"
`;
a === b && b === c; // true
In a single-quoted literal, a single quote must be escaped. In a double-quoted literal, a double quote must be escaped. A raw line break is not allowed in either form, so it has to be written as \n. Template literals accept quotes of both kinds and real line breaks. In a template literal you need to escape the backtick, and you need to escape a dollar sign followed by an opening brace when you want it to appear as text rather than start an interpolation.
const price = `Use \${amount} as a placeholder`; // literal text: ${amount}
const tick = `A backtick: \``; // literal text: A backtick: `
Template literals convert CRLF line endings in the source to LF in the resulting string. A string copied from a Windows-formatted file into a template literal can therefore differ from the original bytes. That matters if you compare it to data that kept the CR characters.
Common escape sequences
| Sequence | Produces | Notes |
| \ | One backslash | Needed in every literal form |
| ' and " | Quote characters | Needed only when they match the delimiter |
| \n, \r, \t | Line feed, carriage return, tab | Required for line breaks in quoted literals |
| \b, \f, \v | Backspace, form feed, vertical tab | Rarely needed |
| \0 | Null character | Must not be followed by a digit |
| \xHH | Code point U+0000 to U+00FF | Exactly two hex digits |
| \uHHHH | One UTF-16 code unit | Exactly four hex digits |
| \u{H...} | Any Unicode code point | Added in ES2015 |
| Backslash at end of line | Nothing (line continuation) | Joins source lines without adding a newline |
Legacy octal escapes such as \251 are a syntax error in strict mode and in template literals. Use \xA9 or \u00A9 instead.
The most common mistake: unescaped backslashes
A backslash always starts an escape sequence, so Windows paths and regular expression text are frequent sources of silent bugs.
'C:\new\table' // C: + newline + "ew" + tab + "able"
'C:\\new\\table' // C:\new\table
String.raw`C:\new\table` // C:\new\table
String.raw keeps backslashes as written. It cannot end with a single trailing backslash, though, because that backslash escapes the closing backtick. For regular expressions, a regex literal is usually easier to read than a string passed to the RegExp constructor, because the string form needs its backslashes doubled.
Unicode escapes, combining marks and emoji
Escaping maps one-to-one onto the code points or code units already in the text. It does not normalize anything. That has consequences for text that looks identical but is stored differently.
'\u00e9' === 'é' // true when é is the precomposed character
'\u0065\u0301' // e + combining acute accent; looks like é
'\u00e9' === '\u0065\u0301' // false
'\u00e9' === '\u0065\u0301'.normalize('NFC') // true
'\u{1F600}' === '\uD83D\uDE00' // true; same emoji
'\u{1F600}'.length // 2 (UTF-16 code units)
An escaped é made of a base letter plus a combining mark is a different string from the precomposed é. Normalize first if your comparisons or lookups depend on matching. Emoji outside the Basic Multilingual Plane take two UTF-16 code units. The \u{...} form writes them as one readable code point. The older \uHHHH form needs both surrogate halves, and a tool that escapes only one half leaves a broken string. Many emoji, such as family groups or flags, are sequences of several code points joined by zero-width joiners or modifiers. Escaping keeps them intact only if every code point is kept in order. A tool that escapes, truncates or reverses per code unit can split them.
Will the result stay readable and usable?
End users and assistive technology
Escape sequences exist only in source code. Once the code runs, the string holds the actual characters, so anything that displays or reads it sees ordinary text, not backslashes. Accessibility of the displayed text depends on the characters themselves, not on how they were written in source. Escaping can still introduce characters that hurt accessibility, such as zero-width or bidirectional control characters, which are invisible on screen but present in the text. How specific screen readers handle those characters was not tested here.
Reviewers and the source code
Escaping helps when a string contains invisible or direction-changing characters, such as U+200B (zero-width space) or U+202E (right-to-left override). Written as raw characters, they can make code look different from how it runs. Bidirectional overrides can even reorder how a line is displayed in some editors. Written as \u200B or \u202E, they are visible and reviewable. Escaping ordinary readable characters does the opposite. It hides meaning behind hex codes and makes the source harder to read.
Search and editing
A text search of the codebase for café will not find caf\u00e9, and a search for a line of copy will miss a version split by \n or line continuations. If people need to find or edit strings by their visible wording, keep the characters literal wherever the syntax allows.
Copying into other formats
An escaped JavaScript literal is not automatically valid elsewhere. JSON requires double quotes and does not accept \x escapes, ' or the \u{...} form, so a JavaScript literal pasted into a JSON file may fail to parse. Other programming languages have their own escape sets. A literal copied between languages should be re-escaped for its new home, not reused as-is.
Going the other way, JSON.stringify produces a double-quoted string that is valid as a JavaScript string literal. Since ES2019 that includes the U+2028 and U+2029 line separators, which earlier versions of the language did not allow inside string literals. That makes JSON.stringify a dependable way to generate an escaped literal from arbitrary text. Its output is not safe to place inside an HTML script element without further handling, because a sequence such as </script> in the string ends the script block. Escaping the less-than character, for example as \u003C, is a common way to avoid this.
Recommendation
- Escape only what the syntax requires: the active quote character, backslashes and line breaks in quoted literals; backticks and the ${ sequence in template literals.
- Use template literals for multi-line text or text with mixed quotes, and keep CRLF-to-LF conversion in mind.
- Write invisible and bidirectional control characters as escapes so reviewers can see them.
- Prefer \u{...} over surrogate pairs for characters outside the Basic Multilingual Plane, and normalize text before comparing if combining marks may be present.
- Keep readable characters as plain text in UTF-8 source, and move long or translatable copy out of code.
- Re-escape for the destination when moving a string into JSON, HTML or another language.
Gaps in this review
No specific online escaping tool was evaluated, so nothing here describes any tool's accuracy, privacy or data retention. Behavior in particular editors, terminals and screen readers was not tested. Statements about them are limited to what follows from the language rules. If you depend on a specific environment, test a sample string that includes quotes, backslashes, a combining mark and a multi-code-point emoji before relying on the output.