Definition
JavaScript string escaping replaces characters that have syntactic or control meaning with escape sequences. A line break can be written as \n, a quotation mark as \", and a Unicode code point as \uXXXX or \u{...}.
const message = "First line\nSecond line";
const symbol = "\u{1F600}";How to escape quotes in JavaScript
A quote must be escaped when it would otherwise close the surrounding string. Prefix it with a backslash, or choose a different delimiter when that keeps the string easier to read.
const single = 'It\'s working';
const double = "He said \"Hello\"";
const easier = 'He said "Hello"';
const template = `A value: ${value}`;Backticks create template literals and allow expressions such as ${value}. To include a literal backtick inside a template literal, write \`. If text is generated rather than written directly in source code, use a serializer such as JSON.stringify() instead of building escape sequences manually.
Common JavaScript escape characters
Quotes and backslash
\' escapes a single quote, \" a double quote and \\ a literal backslash.
Whitespace and controls
\n is a line feed, \r a carriage return, \t a tab and \b a backspace.
Unicode
\u00E9 represents a UTF-16 code unit. Code-point escapes such as \u{1F600} support the full Unicode range.
Escaping a JavaScript string is context-specific
String escaping only creates a valid JavaScript or JSON string representation. It does not automatically make a value safe for HTML, a URL, CSS or a database query. HTML characters require HTML encoding; URL components normally require encodeURIComponent(); JSON data should be produced with JSON.stringify().
Do not confuse three different operations
String escaping
Creates valid source or data-string representations such as \n and \uXXXX.
Legacy escape()
Produces %XX and %uXXXX. It is deprecated and is not a JavaScript string-escaping mechanism.
URI encoding
Represents UTF-8 bytes as percent-encoded sequences for URIs and components.
Need to transform text? Use the JavaScript Escape / Unescape Converter. For URLs, see when to use encodeURI() or encodeURIComponent().