JavaScript HTML encode special characters | Example code

Using replace method you can escape HTML special characters in JavaScript.

HTML encode special characters example in JavaScript

<!DOCTYPE html>
<html>
<body>

  <script>
    function escapeHtml(unsafe) {
      return unsafe
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
    }

    console.log(escapeHtml("&"));
    console.log(escapeHtml("A > B"));
    console.log(escapeHtml("10 > 9"));
  </script>
</body>
</html>

Output:

JavaScript HTML encode special characters

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.