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 "
:
<button onclick="alert('Hello "Mike"')">Click me 2</button>
Reference:
Escaping characters reference
Share "How to escape quotes in JavaScript?"
Related snippets:
- Declare existing global variable in TypeScript
- Check if number is odd or even in JavaScript
- Convert Fahrenheit to Celsius in JavaScript
- Remove double quotes from a string in JavaScript
- Get class name of an object in JavaScript
- Convert milliseconds to minutes and seconds
- Check if an array contains a value
- Append an array to another in JavaScript
- Create HTML element with attributes in JavaScript
- Check if date is valid in JavaScript
- Check if a value is a number in JavaScript
- Check if a string is empty in JavaScript
- Check if string contains a substring in JavaScript
- Get element by ID in React
- Set the required attribute in JavaScript
- Get the first element of an array in JavaScript
- Convert Map values to array in JavaScript
- Escape quotes in JavaScript
- Get elements by data attribute in JavaScript
- Access JavaScript object property with space
- Add class to multiple elements in JavaScript
- Add class to element if it does not already exists with JavaScript
- Add CSS class to body with JavaScript
- Add class to parent element in JavaScript
- Access JavaScript object property with hyphen
- Add new Key - Value pair to an object in JavaScript
Tags:
escape, quote, double quote, html, javascript Technical term:
Escape quotes in JavaScript