Skip to content

Instantly share code, notes, and snippets.

@davidcalhoun
Created June 15, 2011 07:43
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 davidcalhoun/1026657 to your computer and use it in GitHub Desktop.
Save davidcalhoun/1026657 to your computer and use it in GitHub Desktop.
Shortest HTMLEntities in JavaScript ever
/* From Ben McMahan:
http://www.quora.com/What-are-the-most-interesting-HTML-JS-DOM-CSS-hacks-that-most-web-developers-dont-know-about/answer/Ben-McMahan
Example usage:
HTMLEntities('<div id="foo">bar</div>'); // '&lt;div id="foo"&gt;bar&lt;/div&gt;'
*/
function HTMLEntities(a) {
var b = document.createElement('a');
b.innerText = a;
return b.innerHTML;
}
/* And a decoder inspired by the above code
Usage: HTMLEntitiesDecode('&lt;div id="foo"&gt;bar&lt;/div&gt;'); // '<div id="foo">bar</div>'
*/
function HTMLEntitiesDecode(a) {
var b = document.createElement('a');
b.innerHTML = a;
return b.innerText;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment