Skip to content

Instantly share code, notes, and snippets.

@zenbro
Created February 10, 2015 17:27
Show Gist options
  • Save zenbro/60def620ac01c4afc5c1 to your computer and use it in GitHub Desktop.
Save zenbro/60def620ac01c4afc5c1 to your computer and use it in GitHub Desktop.
Sanitize JS
function coerceToString(val) {
return String((val === null || val === undefined) ? '' : val);
}
var rAmp = /&/g,
rLt = /</g,
rGt = />/g,
rApos = /\'/g,
rQuot = /\"/g,
hChars = /[&<>\"\']/;
function sanitize(str) {
str = coerceToString(str);
return hChars.test(str) ?
str
.replace(rAmp, '&amp;')
.replace(rLt, '&lt;')
.replace(rGt, '&gt;')
.replace(rApos, '&#39;')
.replace(rQuot, '&quot;') :
str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment