Skip to content

Instantly share code, notes, and snippets.

@Rob--W
Created November 14, 2016 16:39
Show Gist options
  • Save Rob--W/ec23b9d6db9e56b7e4563f1544e0d546 to your computer and use it in GitHub Desktop.
Save Rob--W/ec23b9d6db9e56b7e4563f1544e0d546 to your computer and use it in GitHub Desktop.
Example of safe HTML escaping using template literals
/* Example:
var someUnsafeStr = '<img>';
var result = escapeHTMLTag`<input value="${someUnsafeStr}">`;
console.log(result); // <input value="&lt;img&gt;">
// Questions? rob {at} robwu.nl
// */
function escapeHTML(str) {
// Note: string cast using String; may throw if `str` is non-serializable, e.g. a Symbol.
// Most often this is not the case though.
return String(str)
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;').replace(/'/g, '&#39;')
.replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
// A tag for template literals that escapes any value as HTML.
function escapeHTMLTag(strings, ...values) {
let results = [];
for (let i = 0; i < strings.length; ++i) {
results.push(strings[i]);
if (i < values.length) { // values[strings.length-1] can be undefined
results.push(escapeHTML(values[i]));
}
}
return results.join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment