Thu Oct 14 2021·2 min read
Photo by Genessa Panainte
To escape a single or double quote in a string, use a backslash
before each single or double quote in the contents of the string, e.g.
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.
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
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.
backticksas 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"
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
const addBackslash = "He said: \\\"test 123\\\"" console.log(addBackslash) // 👉️ He said: \"test 123\"
Here's a more realistic example, where we only add a backslash to the string.
const addBackslash = "BMW \\1996\\" console.log(addBackslash) // 👉️ BMW \1996\
I'll send you 1 email a week with links to all of the articles I've written that week