Last active
November 19, 2023 08:07
-
-
Save amekusa/ffb64222d52d63ec4aa5302a5861bdf4 to your computer and use it in GitHub Desktop.
Convert non-safe chars into HTML entities (JS)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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]};`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This also avoids doubly escaping
&
s.