Last active
June 26, 2018 13:22
-
-
Save jsuryahyd/7ff3be15cf8d7db9d291111cdc253ae0 to your computer and use it in GitHub Desktop.
Escapes HTML characters in a template literal string, to prevent XSS attacks.
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
// 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 = {'&': '&', '<': '<', '>': '>', '"': '"', "'": '''}; | |
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