How to Escape Quotes in a String using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Escape Quotes in a String #

To escape a single or double quote in a string, use a backslash \ character before each single or double quote in the contents of the string, e.g. 'that\'s it'.

index.js
const escapeSingle = 'it\'s a string'; console.log(escapeSingle) // 👉️ it's a string
The backslash character allows us to escape the single quote, so it's interpreted as the literal single quote character, and not as an end of string character.

You can use the same approach to escape a double quote in a string.

index.js
const escapeDouble = "He said: \"test 123\"" console.log(escapeDouble) // 👉️ He said: "test 123"

We use the backslash \ character to escape each double quote in the string.

Escaping a quote can be avoided by changing the outer quotes of the string.
index.js
const withSingle = "it's a string"; console.log(withSingle) // 👉️ it's a string const withDouble = 'He said: "test 123"' console.log(withDouble) // 👉️ He said: "test 123"

We alternate between double and single quotes, so we don't have to escape them.

Note that you can also use backticks as outer quotes for a string. This allows you to use both single and double quotes in the string without having to escape them.
index.js
const withBoth = `it's a "test 123"`; console.log(withBoth) // 👉️ it's a "test 123"
The outer quotes of the string use backticks so we don't have to escape the single or double quotes in the string.

To add a backslash \ character to a string, add two backslashes next to one another. The first backslash escapes the second, so the second is taken literally.

index.js
const addBackslash = "He said: \\\"test 123\\\"" console.log(addBackslash) // 👉️ He said: \"test 123\"

We have 3 backslashes next to one another. The first backslash escapes the second, so it is interpreted literally by JavaScript. The third backslash is used to escape the double quotes.

Here's a more realistic example, where we only add a backslash to the string.

index.js
const addBackslash = "BMW \\1996\\" console.log(addBackslash) // 👉️ BMW \1996\

Further Reading #

Use the search field on my Home Page to filter through my more than 3,000 articles.