Skip to content

Instantly share code, notes, and snippets.

@kafene
Last active August 13, 2025 02:41
Show Gist options
  • Save kafene/41257d8d82bf9ae23dde316049a4c618 to your computer and use it in GitHub Desktop.
Save kafene/41257d8d82bf9ae23dde316049a4c618 to your computer and use it in GitHub Desktop.
Tiny JavaScript functions to entitize/deentitize (escape/unescape) HTML entities
const [ entitize, deentitize ] = (charmap => [
h => charmap.reduce((v, [char, entity]) => v.replaceAll(char, entity), h),
h => charmap.reduce((v, [char, entity]) => v.replaceAll(entity, char), h),
])([['&','&amp;'],['<','&lt;'],['>','&gt;'],['"','&quot;'],["'",'&#039;']]);
// minified
const [e,d]=(m=>[h=>m.reduce((v,[c,e])=>v.replaceAll(c,e),h),h=>m.reduce((v,[c,e])=>v.replaceAll(e,c),h)])([['&','&amp;'],['<','&lt;'],['>','&gt;'],['"','&quot;'],["'",'&#039;']]);
// example
var html = '<b>You & I really just "<i>get it</i>", don\'t we?</b>';
var entitized = '&lt;b&gt;You &amp; I really just &quot;&lt;i&gt;get it&lt;/i&gt;&quot;, don&#039;t we?&lt;/b&gt;';
console.log(entitize(html) === entitized, entitize(html));
console.log(deentitize(entitized) === html, deentitize(entitized));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment