Last active
August 29, 2015 14:01
-
-
Save moust/1cd4b5414e01cdf048b6 to your computer and use it in GitHub Desktop.
JavaScript escapeString function
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 escape = { | |
"&": "&", | |
"<": "<", | |
">": ">", | |
'"': """, | |
"'": "'", | |
"`": "`" | |
}; | |
var badChars = /[&<>"'`]/g; | |
var possible = /[&<>"'`]/; | |
function escapeChar(chr) { | |
return escape[chr] || "&"; | |
} | |
function escapeString(string) { | |
if (!string && string !== 0) { | |
return ""; | |
} | |
// Force a string conversion as this will be done by the append regardless and | |
// the regex test will do this transparently behind the scenes, causing issues if | |
// an object's to string has escaped characters in it. | |
string = "" + string; | |
if(!possible.test(string)) { return string; } | |
return string.replace(badChars, escapeChar); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment