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, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
document.write(escapeHtml(str));
</script>
</script>
</body>
</html>
Output:
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