Skip to content

JavaScript escape quotes in a string | Example code

  • by

You will need to use regular expressions 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 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

Leave a Reply

Your email address will not be published. Required fields are marked *