Skip to content

Instantly share code, notes, and snippets.

@kernusr
Last active July 7, 2019 12:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kernusr/c1dfa96bc5b2cfd6daa931ad22268fa1 to your computer and use it in GitHub Desktop.
Save kernusr/c1dfa96bc5b2cfd6daa931ad22268fa1 to your computer and use it in GitHub Desktop.
Analogue of functions htmlspecialchars() and htmlspecialchars_decode() for JavaScript
function escapeHtml(text, decode = false) {
var map = decode ? {
'&' : '&',
'&lt;' : '<',
'&gt;' : '>',
'&quot;' : '"',
'&#039;' : "'"
} : {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#039;'
},
regex = decode ? /(&amp;|&lt;|&gt;|&quot;|&#039;)/g : /[&<>"']/g;
return text.replace(regex, function(m) { return map[m]; });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment