JavaScript escape quotes in a string | Example code

You will need to use regular expression to escape quotes in a string in JavaScript.

Escape Character

CodeResultDescription
\’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:

JavaScript escape quotes in a string

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 and 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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.