String.prototype.replace()
with a regexp that matches the characters that need to be escaped.const escapeHTML = str =>
str.replace(
/[&<>'"]/g,
tag =>
({
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"'
}[tag] || tag)
);
escapeHTML('<a href="#">Me & you</a>');
// '<a href="#">Me & you</a>'
Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️