Skip to content

Instantly share code, notes, and snippets.

@claystreet
Created June 24, 2013 22:49
Show Gist options
  • Save claystreet/5854418 to your computer and use it in GitHub Desktop.
Save claystreet/5854418 to your computer and use it in GitHub Desktop.
An HTML escape function for JavaScript with three regex choices based on your need. 1. simple regex but recursively escapes "&" (similar to many html escape functions available today) 2. moderate regex won't double escape "&" 3. more complex regex won't double escape "&" on any char ref Uncomment the regex you want to use and comment out the…
var escapeHtml = (function() {
var entityMap = {
"&": '&',
"<": '&lt;',
">": '&gt;',
'"': '&quot;',
"'": '&#39;',
"/": '&#x2F;'
},
// simple but will recursively/blindly escape "&"
// (a string may change every time it is escaped)
//rxHtmlEscape = /[&<>"'\/]/g;
// won't double escape "&amp;"
// (a string may change the first and second time it is escaped but not thereafter)
//rxHtmlEscape = /[<>"'\/]|&(amp;)?/g;
// won't escape "&" on any existing char refs
// (a string will only change the first time it is escaped)
rxHtmlEscape = /[<>"'\/]|&([a-zA-Z0-9]{2,6};|#[0-9]{1,5};|#x[0-9a-fA-F]{1,4};)?/g;
return function(str) {
return String(str).replace(rxHtmlEscape, function(s) {
if (s in entityMap) return entityMap[s];
return s;
});
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment