Created
August 11, 2020 20:39
-
-
Save jsteemann/92e660642bc8a511315abe7888bc4fd5 to your computer and use it in GitHub Desktop.
Decode HTML entities in a string
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
/* | |
* decode HTML entities in a string | |
* usage examples: | |
* htmlDecode('foo & bar') => 'foo & bar' | |
* htmlDecode('foo/bar') => 'foo/bar' | |
*/ | |
let htmlDecode = function(str) { | |
const map = { | |
'&' : '&', | |
'>' : '>', | |
'<' : '<', | |
'"': '"', | |
''' : "'" | |
}; | |
// 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