Last active
October 11, 2015 09:38
-
-
Save arnehormann/3839134 to your computer and use it in GitHub Desktop.
escape text for inclusion by innerHTML as one handy fully namespaced function
This file contains hidden or 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 regexp = /[<>&'"\/]/g | |
, replacements = | |
{ '&': '&' | |
, '<': '<' | |
, '>': '>' | |
, '/': '/' | |
, '"': '"' | |
, "'": ''' | |
} | |
, replacer = function(match) { | |
return replacements[match] | |
} | |
return function(string) { | |
return String(string).replace(regexp, replacer) | |
} | |
})() |
Have a look at http://js-quasis-libraries-and-repl.googlecode.com/svn/trunk/safetemplate.html first. All simple approaches for HTML-escaping come with a lot of problems.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found some great advice on text-escaping at http://benv.ca/2012/10/4/you-are-probably-misusing-DOM-text-methods/ - but I prefer it this way.