Skip to content

Instantly share code, notes, and snippets.

@moust
Last active August 29, 2015 14:01
Show Gist options
  • Save moust/1cd4b5414e01cdf048b6 to your computer and use it in GitHub Desktop.
Save moust/1cd4b5414e01cdf048b6 to your computer and use it in GitHub Desktop.
JavaScript escapeString function
var escape = {
"&": "&",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#x27;",
"`": "&#x60;"
};
var badChars = /[&<>"'`]/g;
var possible = /[&<>"'`]/;
function escapeChar(chr) {
return escape[chr] || "&amp;";
}
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