Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save ichim-david/5060507b8f34a55de40459e88e6c3303 to your computer and use it in GitHub Desktop.

Select an option

Save ichim-david/5060507b8f34a55de40459e88e6c3303 to your computer and use it in GitHub Desktop.
The fastest way to escape HTML strings known to me~~n~~, if you need to do so with JS and you are inside a browser.
// Can you make this faster? Ping me.
const escapeHtml = (function () {
const serializer = new XMLSerializer ();
const attr = document.createAttribute ( 'attr' );
const re = /[&<>"]/;
return function escapeHtml ( str ) {
if ( !re.test ( str ) ) return str;
attr.value = str;
return serializer.serializeToString ( attr );
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment