JavaScript escape HTML | Example code

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 a HTML special characters in JavaScript.

<!DOCTYPE html>

   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;");




JavaScript escape HTML

Do comment if you have any doubts and 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

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