Skip to content

Instantly share code, notes, and snippets.

@bethrezen
Created May 21, 2017 10:09
Show Gist options
  • Select an option

  • Save bethrezen/2a9584776f40cafca794b90e429daa0a to your computer and use it in GitHub Desktop.

Select an option

Save bethrezen/2a9584776f40cafca794b90e429daa0a to your computer and use it in GitHub Desktop.
es6 template tag for html escaping
// HTML Escape helper utility
const util = (function () {
// Thanks to Andrea Giammarchi
const reEscape = /[&<>'"]/g;
const reUnescape = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g;
const oEscape = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'\'': '&#39;',
'"': '&quot;'
};
const oUnescape = {
'&amp;': '&',
'&#38;': '&',
'&lt;': '<',
'&#60;': '<',
'&gt;': '>',
'&#62;': '>',
'&apos;': '\'',
'&#39;': '\'',
'&quot;': '"',
'&#34;': '"'
};
const fnEscape = function (m) {
return oEscape[m];
};
const fnUnescape = function (m) {
return oUnescape[m];
};
const replace = String.prototype.replace;
return (Object.freeze || Object)({
escape: function escape(s) {
return replace.call(s, reEscape, fnEscape);
},
unescape: function unescape(s) {
return replace.call(s, reUnescape, fnUnescape);
}
});
}());
// Tagged template function
const html = (pieces, ...substitutions) => {
let result = pieces[0];
for (let i = 0; i < substitutions.length; ++i) {
result += util.escape(substitutions[i]) + pieces[i + 1];
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment