To escape HTML special chars in JavaScript, we call the replaceAll
method.
For instance, we write
const escapeHtml = (unsafe) => {
return unsafe
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
};
to define the escapeHtml
function.
In it, we call replaceAll
to replace all the strings in the first argument with the ones in the 2nd argument.
Therefore, all the HTML characters are replaced with their corresponding HTML entities.
The string with the replacements done is returned.