How to Escape Quotes in a String using JavaScript

avatar

Borislav Hadzhiev

Thu Oct 14 20212 min read

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 taken literally in the string.

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"

Again, we use the backslash \ character to escape each double quote in the string.

Escaping a quote can be avoided in most cases, 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"

In the examples, we alternate between outer and inner 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\"

In the example above 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\

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee