Created
June 24, 2013 22:49
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var escapeHtml = (function() { | |
var entityMap = { | |
"&": '&', | |
"<": '<', | |
">": '>', | |
'"': '"', | |
"'": ''', | |
"/": '/' | |
}, | |
// simple but will recursively/blindly escape "&" | |
// (a string may change every time it is escaped) | |
//rxHtmlEscape = /[&<>"'\/]/g; | |
// won't double escape "&" | |
// (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