Skip to content

Instantly share code, notes, and snippets.

@codesorter2015
Forked from Rob--W/escaopeHTMLTag.js
Created April 11, 2018 10:18
Show Gist options
  • Save codesorter2015/8b5f9f773577e438b29aa97285271cd3 to your computer and use it in GitHub Desktop.
Save codesorter2015/8b5f9f773577e438b29aa97285271cd3 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