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, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
console.log(escapeHtml("&"));
console.log(escapeHtml("A > B"));
console.log(escapeHtml("10 > 9"));
</script>
</body>
</html>
Output:
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