How to Escape Quotes in a String using JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 2, 2024
4 min

banner

# Table of Contents

  1. Escape Quotes in a String in JavaScript
  2. Escaping double quotes in a String
  3. Escaping quotes in a String with String.replaceAll()
  4. Alternating quotes to avoid using backslashes
  5. Using backticks instead of backslashes
  6. Showing the escape characters in a string
  7. Avoiding inline event handlers in HTML code

# Escape Quotes in a String in JavaScript

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 const escapeDouble = "bobby\"hadz" console.log(escapeDouble) // ๐Ÿ‘‰๏ธ bobby"hadz

escape quotes in string

The code for this article is available on GitHub
When we use the backslash character to escape a single or a double quote, we instruct JavaScript that we want to treat the quote as a literal single or double quote character and not as an end-of-string character.

If you use a single quote in a string that is wrapped in single quotes, you would terminate the string prematurely.

However, this is not the case when you use a backslash to escape the single quote.

# Escaping double quotes in a 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"

escape double quotes in string

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

# Escaping quotes in a String with String.replaceAll()

You can also use the String.replaceAll() method to escape the quotes in a string.

index.js
// โœ… escape every single quote const str = "it's a string"; console.log(str); // ๐Ÿ‘‰๏ธ it's a string const result = str.replaceAll("'", "\\'"); console.log(result); // ๐Ÿ‘‰๏ธ it\'s a string

escaping quotes in string with string replaceall

The code for this article is available on GitHub

The String.replaceAll() method returns a new string with all matches of a pattern replaced by the provided replacement.

The method takes the following parameters:

NameDescription
patternThe pattern to look for in the string. Can be a string or a regular expression.
replacementA string used to replace the substring match by the supplied pattern.

The code sample escapes every single quote in a string.

index.js
// โœ… escape every single quote const str = "it's a string"; console.log(str); // ๐Ÿ‘‰๏ธ it's a string const result = str.replaceAll("'", "\\'"); console.log(result); // ๐Ÿ‘‰๏ธ it\'s a string

The same approach can be used to escape double quotes in a string.

index.js
// โœ… escape every double quote const str = 'it"s a string'; console.log(str); // ๐Ÿ‘‰๏ธ it"s a string const result = str.replaceAll('"', '\\"'); console.log(result); // ๐Ÿ‘‰๏ธ it\"s a string

The String.replaceAll() method returns a new string with the matches of the pattern replaced. The method doesn't change the original string.

Strings are immutable in JavaScript.

# Alternating quotes to avoid using backslashes

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"

alternating quotes to avoid using backslashes

The code for this article is available on GitHub

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

# Using backticks instead of backslashes

Note that you can also use backticks when defining a variable that stores 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"

using backticks instead of backslashes

The string is wrapped in backticks so we don't have to escape the single and double quotes in its contents.

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\

# Showing the escape characters in a string

If you need to show the escape characters in a string, use the JSON.stringify() method.

index.js
const addBackslash = 'BMW \\1996\\'; console.log(addBackslash); // ๐Ÿ‘‰๏ธ BMW \1996\ const withEscapeChars = JSON.stringify(addBackslash); console.log(withEscapeChars); // ๐Ÿ‘‰๏ธ "BMW \\1996\\"
The code for this article is available on GitHub

The JSON.stringify method converts a JavaScript value to a JSON string.

When a value is converted to a JSON string, its output contains the escape characters.

# Avoiding inline event handlers in HTML code

If you get the error when using inline event handlers in HTML code, the best solution is to rewrite your code to use JavaScript and not use an inline event handler.

Here is an example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">bobbyhadz.com</div> <script type="module" src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); function handleClick() { box.style.background = 'lime'; } box.addEventListener('click', handleClick); box.innerHTML = ` <div id="box"> <p title="example">bobbyhadz.com</p> <p>Hello world</p> </div> `;

You can select the DOM element using the document.getElementById() method or the querySelector method.

Then you can add an event listener to the element or update its inner HTML markup.

Notice that we used backticks when setting the innerHTML property.

This enables us to use both single and double quotes when constructing the HTML markup.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev