Sometimes, we want to escape HTML special characters in JavaScript.
In this article, we’ll look at how to escape HTML special characters in JavaScript.
How to escape HTML special characters in JavaScript?
To escape HTML special characters in JavaScript, we replace all the special HTML characters with HTML entities.
For instance, we write
const escapeHtml = (unsafe) => {
return unsafe
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
};
to call replaceAll
with the characters to replace and the HTML entities to replace them with respectively.
Conclusion
To escape HTML special characters in JavaScript, we replace all the special HTML characters with HTML entities.