Skip to content

Instantly share code, notes, and snippets.

@Crydust
Last active January 19, 2016 10:24
Show Gist options
  • Save Crydust/8d41a132559ca20ea4ab to your computer and use it in GitHub Desktop.
Save Crydust/8d41a132559ca20ea4ab to your computer and use it in GitHub Desktop.
// adapted from MIT licensed handlebars
var escape = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#x27;',
'`': '&#x60;',
'=': '&#x3D;',
' ': '&#x20;'
};
var badChars = /[&<>"'`= ]/g;
var possible = /[&<>"'`= ]/;
function escapeChar(chr) {
return escape[chr];
}
function escapeExpression(string) {
if (typeof string !== 'string') {
if (string == null) {
return '';
} else if (!string) {
return string + '';
}
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