If you are saving this information in a database, its wrong to escape HTML using a client-side script, this should be done in the server. Otherwise its easy to bypass your XSS protection.
To make my point clear, here is a exemple using one of the answers:
Lets say you are using the function escapeHtml to escape the Html from a comment in your blog and then posting it to your server.
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
function escapeHtml(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
The user could:
- Edit the POST request parameters and replace the comment with javascript code.
- Overwrite the escapeHtml function using the browser console.
If the user paste this snippet in the console it would bypass the XSS validation:
function escapeHtml(string){
return string
}