Skip to content

Instantly share code, notes, and snippets.

@englishextra
Last active May 12, 2016 11:21
Show Gist options
  • Save englishextra/737e35d19bcb4ee62ab85c9f9b292842 to your computer and use it in GitHub Desktop.
Save englishextra/737e35d19bcb4ee62ab85c9f9b292842 to your computer and use it in GitHub Desktop.
A minimal html entities decoder/encoder using DOM
/*!
* A minimal html entities decoder/encoder using DOM.
* gist.github.com/englishextra/737e35d19bcb4ee62ab85c9f9b292842
* modified github.com/jussi-kalliokoski/htmlentities.js
* see issue github.com/jussi-kalliokoski/htmlentities.js/issues/1
* htmlentities.encode('<&>'); returns '&lt;&amp;&gt;';
* htmlentities.decode('&lt;&amp;&gt;'); returns '<&>';
* htmlentities is a shorthand for htmlentities.encode
*/
var htmlentities = (function (a) {
function e(s) {
return s = s.replace(/[<!="'\/>&]/g, function (char) {
return {
"<" : "&lt;",
"!" : "&#033;",
"=" : "&#061;",
'"' : "&quot;",
"'" : "&apos;",
"/" : "&#047;",
">" : "&gt;",
"&" : "&amp;"
}
[char];
});
}
function b(c) {
var d = a.createElement("div");
d.appendChild(a.createTextNode(c));
c = e(d.innerHTML);
d = null;
return c;
}
b.decode = function (c) {
var d = a.createElement("div");
d.innerHTML = c;
c = e(d.innerText || d.textContent);
d = null;
return c;
};
return (b.encode = b)
}
(document));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment