Skip to content

Instantly share code, notes, and snippets.

@bg5sbk
Last active December 30, 2015 16:28
Show Gist options
  • Save bg5sbk/7854590 to your computer and use it in GitHub Desktop.
Save bg5sbk/7854590 to your computer and use it in GitHub Desktop.
HTML encode and decode in JavaScript.
function html_encode(str) {
var s = "";
if (str.length == 0) return "";
s = str.replace(/&/g, "&");
s = s.replace(/</g, "&lt;");
s = s.replace(/>/g, "&gt;");
s = s.replace(/\'/g, "&#39;");
s = s.replace(/\"/g, "&quot;");
return s;
}
function html_decode(str) {
var s = "";
if (str.length == 0) return "";
s = str.replace(/&amp;/g, "&");
s = s.replace(/&lt;/g, "<");
s = s.replace(/&gt;/g, ">");
s = s.replace(/&#39;/g, "\'");
s = s.replace(/&quot;/g, "\"");
return s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment