Skip to content

JavaScript escape a single quote in a string variable | Example code

  • by

Using Regex and replace method will escape single quote in string variable in JavaScript.

<!DOCTYPE html>
<html>
<body>
  <div id="div1">Men's and Women's something.</div>
  <script>

    var str =  document.getElementById("div1").innerHTML;
    console.log(str.replace(/'/g,"\\'"));
  </script>
</body>
</html>

Output:

JavaScript escape a single quote in a string variable

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading