Skip to content

Instantly share code, notes, and snippets.

@jsteemann
Created August 11, 2020 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsteemann/92e660642bc8a511315abe7888bc4fd5 to your computer and use it in GitHub Desktop.
Save jsteemann/92e660642bc8a511315abe7888bc4fd5 to your computer and use it in GitHub Desktop.
Decode HTML entities in a string
/*
* decode HTML entities in a string
* usage examples:
* htmlDecode('foo & bar') => 'foo & bar'
* htmlDecode('foo/bar') => 'foo/bar'
*/
let htmlDecode = function(str) {
const map = {
'&' : '&',
'>' : '>',
'&lt;' : '<',
'&quot;': '"',
'&#39;' : "'"
};
// this could easily be optimized so that the regex is only
// generated on the first call. right now it is re-generated
// on every function invocation.
const re = new RegExp('(' + Object.keys(map).join('|') + '|&#[0-9]{1,5};|&#x[0-9a-fA-F]{1,4};' + ')', 'g');
return String(str).replace(re, function(match, capture) {
return (capture in map) ? map[capture] :
capture[2] === 'x' ?
String.fromCharCode(parseInt(capture.substr(3), 16)) :
String.fromCharCode(parseInt(capture.substr(2), 10));
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment