JavaScript String Escaping Rules and Best Practices

Complete guide to string escaping in JavaScript and TypeScript. Covers single quotes, double quotes, template literals, Unicode escapes, and JSON.stringify for safe serialization.

Language-Specific

Detailed Explanation

JavaScript String Escaping

JavaScript offers three string delimiters — single quotes ('), double quotes ("), and backticks (```) — each with slightly different escaping rules. Understanding these differences is key to writing clean, bug-free code.

Single and Double Quoted Strings

Both behave identically in terms of escape sequences. The only difference is which delimiter must be escaped:

'It\'s escaped'     // escape single quote inside single-quoted string
"She said \"hi\""  // escape double quote inside double-quoted string

Supported Escape Sequences

\\'   → single quote
\\"   → double quote
\\\\   → backslash
\\n   → newline
\\r   → carriage return
\\t   → tab
\\b   → backspace
\\f   → form feed
\\0   → null character
\\uXXXX   → Unicode BMP character (4 hex digits)
\\u{XXXXX} → Unicode code point (ES6+, 1-6 hex digits)
\\xHH  → Latin-1 character (2 hex digits)

Template Literals (Backtick Strings)

Template literals handle most characters without escaping. You only need to escape backticks and the ${ sequence:

const msg = \`She said "it's fine"\`;       // no escaping needed
const code = \`Use \\\` for template literals\`; // escape backtick
const raw = \`Cost: \\${amount}\`;             // escape interpolation

JSON.stringify for Safe Escaping

When embedding data in JSON or HTML, JSON.stringify() handles all necessary escaping automatically:

const data = 'Line 1\nLine 2\t"quoted"';
console.log(JSON.stringify(data));
// Output: "Line 1\nLine 2\t\"quoted\""

Tagged Template Literals

The String.raw tag returns the raw string without processing escapes:

String.raw\`\n\t\`  // returns the four characters: \ n \ t

Common Mistakes

  • Forgetting to escape backslashes in regex: new RegExp("\\\\d+") not new RegExp("\\d+").
  • Using \x with only one hex digit — JavaScript requires exactly two.
  • Assuming template literals need single/double quote escaping — they do not.

Use Case

JavaScript string escaping knowledge is essential for frontend and backend developers working with DOM manipulation, JSON APIs, dynamic HTML generation, template engines, regex construction, database queries, and any scenario where user input must be safely embedded in strings to prevent XSS or injection attacks.

Try It — String Escape/Unescape

Open full tool