Escape characters are symbols that tell the computer to do something special. For example, the escape character for a new line is
"\n" which tells the computer to start a new line.
There are two ways to print quotes using escape characters:
- For single quotes: \’ (backslash followed by single quote)
- For double quotes: \” (backslash followed by double quotes)
Escape Quotes in a String
If you want to include a single or double quote in a string, you can escape it by putting a backslash character in front of it. For example, if you want to include the following in a string: ‘it’s a string’, you would write it as ‘it’s a string’.
ℹ️ The backslash character can be used to escape the single quote, so that it is interpreted as a literal single quote character, rather than as an end of string character.
const escapeSingle = 'it\'s a escape string'; console.log(escapeSingle)
To escape a double quote in a string, use the same approach as you would for a single quote.
const escapeDoubleQuote = "Hello said: \"Hey!\"" console.log(escapeDoubleQuote)
To escape each double quote in the string, use the backslash character.
You can avoid having to escape a quote by changing the outer quotes of the string.
const withSingleQuote = "it's a string"; console.log(withSingleQuote) const withDoubleQuote = 'He said: "test 123"' console.log(withDoubleQuote)
We alternate between double and single quotes, so that we don’t have to escape them.
You can 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.
const withBacktick = `it's a "test 123"`; console.log(withBacktick);
ℹ️ Use backticks to enclose the outer quotes of the string, so you don’t have to escape the single or double quotes within the string.
If you want to add a backslash to a string, you need to add two backslashes next to each other. The first backslash will escape the second one, so the second backslash will be taken literally.
const addBackslash = "He said: \"test 123\"" console.log(addBackslash)
Here’s an example that’s more realistic, where we only add a backslash to the string.
const addBackslash = "Year \2022\" console.log(addBackslash)