Skip to content

JavaScript escape HTML | Example code

  • by

Use replace() method to escape HTML in JavaScript. You can easily escape HTML special characters.

Example JavaScript escape HTML

Display text to HTML webpage using JavaScript function with escaping an HTML special characters in JavaScript.

<!DOCTYPE html>
<html>
<body>

  <script>
   let str = 'Hello World "This" is some sample Text & 10>2 ';
   function escapeHtml(unsafe) {
    return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
  }

  document.write(escapeHtml(str));

</script>
</script>
</body>
</html>

Output:

JavaScript escape HTML

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 *