JavaScript escape for string literals
A JavaScript escape converts text so it can be pasted between quotes in source code without breaking the syntax. Multi-line text, Windows paths full of backslashes and messages containing both kinds of quotes are the usual trouble makers; this tool fixes all of them in one step.
Escape sequences produced
| Character | Escaped as |
|---|---|
| Backslash | \\ |
| Double / single quote | \" / \' |
| Line feed, carriage return, tab | \n, \r, \t |
| Backspace, form feed, vertical tab | \b, \f, \v |
| NUL | \0 |
| Other control characters (U+0001–U+001F, U+007F) | \xHH, e.g. \x1B |
| Line / paragraph separator (U+2028, U+2029) | \u2028, \u2029 |
Both quote types are escaped, so the result works in single-quoted and double-quoted strings. U+2028 and U+2029 are escaped because they were illegal inside string literals before ES2019 and still break older tools and JSONP responses.
Example
Input:
Line 1
Say "hi" — it's C:\newOutput:
Line 1\nSay \"hi\" — it\'s C:\\newWith Escape non-ASCII as \uXXXX ticked, the same input becomes:
Line 1\nSay \"hi\" \u2014 it\'s C:\\newCharacters outside the Basic Multilingual Plane, such as emoji, are written as a surrogate pair (\uD83D\uDE80 for 🚀), which every JavaScript engine understands.
Template literals and HTML pages
- The output is meant for
'…'or"…"strings. In a template literal you would additionally need to escape the backtick and${. - If the string goes inside an inline
<script>block in an HTML page, the sequence</script>would still end the script early. Split it (<\/script>) or pass data through a JSONdata-attribute instead. - For JSON documents, which have stricter rules (no
\', no\x), use JSON Escape.
Escaping strings in code
When you generate JavaScript from a program, the simplest reliable approach is JSON.stringify(value): since ES2019 every JSON string is also a valid JavaScript string literal, quotes included. Hand escaping with this tool is most useful for constants you paste into source files, test fixtures, bookmarklets and snippets typed into a browser console, where you want readable output rather than a full serializer.
The ASCII-only option is worth ticking when a file will be served or bundled without an explicit UTF-8 charset, or when a build step expects plain ASCII. Many bundlers and minifiers have a similar setting for the same reason.
Reverse the process with JavaScript Unescape. The tool runs locally in your browser.