You will need to use regular expressions to escape quotes in a string in JavaScript.
Escape Character
Code | Result | Description |
---|---|---|
\’ | ‘ | Single quote |
\” | “ | Double quote |
\\ | \ | Backslash |
How to escape quotes in a string in JavaScript
HTML example code.
Double Quote
<!DOCTYPE html>
<html>
<body>
<script>
var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/"/g, '\\"');
alert(var1);
</script>
</body>
</html>
Output:

Single Quote
<!DOCTYPE html>
<html>
<body>
<script>
var str = "Dude, he totally said that 'You Rock!'";
var var1 = str.replace("'", "\\'");
alert(var1);
</script>
</body>
</html>
Note: Check out more on regular expressions here.
Do comment if you have any doubts or suggestions on this JS escape code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version