Skip to content

Instantly share code, notes, and snippets.

@fabiospampinato
Created June 2, 2021 13:41
Show Gist options
  • Save fabiospampinato/a2a38148f76188cebaabd1bea41dddb0 to your computer and use it in GitHub Desktop.
Save fabiospampinato/a2a38148f76188cebaabd1bea41dddb0 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