Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
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'
.
const escapeSingle = 'it\'s a string'; console.log(escapeSingle) // 👉️ it's a string
You can use the same approach to escape a double quote in a string.
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.
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.
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.const withBoth = `it's a "test 123"`; console.log(withBoth) // 👉️ it's a "test 123"
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.
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.
const addBackslash = "BMW \\1996\\" console.log(addBackslash) // 👉️ BMW \1996\