Skip to content

Instantly share code, notes, and snippets.

@jsuryahyd
Last active June 26, 2018 13:22
Show Gist options
  • Save jsuryahyd/7ff3be15cf8d7db9d291111cdc253ae0 to your computer and use it in GitHub Desktop.
Save jsuryahyd/7ff3be15cf8d7db9d291111cdc253ae0 to your computer and use it in GitHub Desktop.
Escapes HTML characters in a template literal string, to prevent XSS attacks.
// Escapes HTML characters in a template literal string, to prevent XSS.
// See https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet#RULE_.231_-_HTML_Escape_Before_Inserting_Untrusted_Data_into_HTML_Element_Content
function sanitizeHTML(strings) {
const entities = {'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'};
let result = strings[0];
for (let i = 1; i < arguments.length; i++) {
result += String(arguments[i]).replace(/[&<>'"]/g, (char) => {
return entities[char];
});
result += strings[i];
}
return result;
}
function htmlEncode(str){
if(str == undefined){
return "";
}
str = str.replace(/[\0\1\2\3\4\5\6\7]/g, '');
return str;
}
function htmlToPlainText(str){
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment