Just going through all my little libraries, and found this tiny gem that's been quite useful.
function htmlSpecialChars(str) {
return str.replace(/[&<>"']/g, function(m) {
return '&#38;#' + m.charCodeAt() + ';';
});
}
Nothing fancy, but it works. It escapes enough characters to make an HTML string not render as code should you be forced to innerHTML or other wise slop it into the document.
*** NOTE *** when possible if this is a issue, try to use Element.textContent or document.createTextNode instead of this. Still it's nice to have for when decisions about whether or not to go full Gungan with innerHTML is out of your hands.