-
-
Save codesorter2015/8b5f9f773577e438b29aa97285271cd3 to your computer and use it in GitHub Desktop.
Revisions
-
Rob--W created this gist
Nov 14, 2016 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,28 @@ /* Example: var someUnsafeStr = '<img>'; var result = escapeHTMLTag`<input value="${someUnsafeStr}">`; console.log(result); // <input value="<img>"> // 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, '&') .replace(/"/g, '"').replace(/'/g, ''') .replace(/</g, '<').replace(/>/g, '>'); } // 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(''); }