Skip to content

Instantly share code, notes, and snippets.

@sultaniman
Created November 8, 2016 13:40
Show Gist options
  • Select an option

  • Save sultaniman/2f5d6bd8829142a3a3f14eeac92a17ea to your computer and use it in GitHub Desktop.

Select an option

Save sultaniman/2f5d6bd8829142a3a3f14eeac92a17ea to your computer and use it in GitHub Desktop.
Sanitize HTML inspired by Ember
const escape = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
// jscs:disable
"'": '&#x27;',
// jscs:enable
'`': '&#x60;',
'=': '&#x3D;'
};
const possible = /[&<>"'`=]/;
const badChars = /[&<>"'`=]/g;
function escapeChar(chr) {
return escape[chr];
}
export function escapeExpression(string) {
if (typeof string !== 'string') {
if (string == null) {
return '';
} else if (!string) {
return string + '';
}
// 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.replace(badChars, escapeChar);
}
return string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment