-
-
Save codesorter2015/8b5f9f773577e438b29aa97285271cd3 to your computer and use it in GitHub Desktop.
Example of safe HTML escaping using template literals
This file contains 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 characters
/* 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(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment