Skip to content

JavaScript HTML encode special characters | Example code

  • by

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

HTML encode special characters example in JavaScript

Simple example code.

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

Do comment if you have any doubts or suggestions on this JS example 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 *