Skip to content

Instantly share code, notes, and snippets.

@amekusa
Last active November 19, 2023 08:07
Show Gist options
  • Save amekusa/ffb64222d52d63ec4aa5302a5861bdf4 to your computer and use it in GitHub Desktop.
Save amekusa/ffb64222d52d63ec4aa5302a5861bdf4 to your computer and use it in GitHub Desktop.
Convert non-safe chars into HTML entities (JS)
/**
* Converts non-safe chars into HTML entities.
* @author amekusa
*/
function escape(str) {
if (!str) return '';
let map = {
'&': 'amp',
'"': 'quot',
"'": 'apos',
'<': 'lt',
'>': 'gt'
};
let ents = Object.values(map).join('|'); // to avoid double-escape '&'s
let find = new RegExp(`["'<>]|(&(?!${ents};))`, 'g'); // regex negative match = (?!word)
return `${str}`.replace(find, found => `&${map[found]};`);
}
@amekusa
Copy link
Author

amekusa commented Nov 19, 2023

This also avoids doubly escaping &s.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment