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

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

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