- Instant help with your JavaScript coding problems

Escape quotes in JavaScript

Question:
How to escape quotes in JavaScript?
Answer:
// JavaScript context
alert("Hello \"Mike\"!");

// HTML context
alert('Hello "Mike"!')
Description:

To escape quotes ' and double quotes " in a JavaScript string use the \ escape character.

const myString1 = "Hello \"Mike\"";
const myString2 = 'Hello \'Mike\'';

However you can eleminiate this problem and make your code more readable if you choose qutes carefully. If you use different types of string separator quotes than the quotes inside your string then no escaping is required:

const myString1 = "Hello 'Mike'";
const myString2 = "Hello 'Mike'";
const myString3 = `Hello 'Mike'`;

In case of an HTML context the situation is a bit more complex as the following code results a syntax error:

<button onclick="alert('Hello \"Mike\"!')">Click me 2</button>

In such cases you need to use HTML enities, so instead of " use &quot; :

<button onclick="alert('Hello &quot;Mike&quot;')">Click me 2</button>
Share "How to escape quotes in JavaScript?"