Skip to content

Instantly share code, notes, and snippets.

@RickyLin
Created November 22, 2021 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RickyLin/fa044c46ee17a2f6decf6a737d933fd4 to your computer and use it in GitHub Desktop.
Save RickyLin/fa044c46ee17a2f6decf6a737d933fd4 to your computer and use it in GitHub Desktop.
HtmlEncode and HtmlDecode in Javascript
/* source: https://stackoverflow.com/a/7124052/2753545 */
function htmlEscape(str) {
return str
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/\//g, '&#x2F;');
}
// I needed the opposite function today, so adding here too:
function htmlUnescape(str){
return str
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&amp;/g, '&')
.replace(/&#x2F;//g, '\\');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment