Created
February 10, 2015 17:27
-
-
Save zenbro/60def620ac01c4afc5c1 to your computer and use it in GitHub Desktop.
Sanitize JS
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
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, '&') | |
.replace(rLt, '<') | |
.replace(rGt, '>') | |
.replace(rApos, ''') | |
.replace(rQuot, '"') : | |
str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment