I think you can use the functions from a question on a slightly different subject (Efficiently replace all accented characters in a string?).
Jason Bunting's answer has some nice ideas + the necessary explanation, here is his solution with some modifications to get you started (if you find this helpful, upvote his original answer as well, as this is his code, essentially).
var replaceHtmlEntites = (function() {
var translate_re = /&(nbsp|amp|quot|lt|gt);/g,
translate = {
'nbsp': String.fromCharCode(160),
'amp' : '&',
'quot': '"',
'lt' : '<',
'gt' : '>'
},
translator = function($0, $1) {
return translate[$1];
};
return function(s) {
return s.replace(translate_re, translator);
};
})();
callable as
var stringToMatch = "This string has special chars & and &nbsp;";
var stringOutput = replaceHtmlEntites(stringToMatch);
Numbered entites are even easier, you can replace them much more generically using a little math and String.fromCharCode()
.
Another, much simpler possibility would be like this (works in any browser)
function replaceHtmlEntites(string) {
var div = document.createElement("div");
div.innerHTML = string;
return div.textContent || div.innerText;
}
replaceHtmlEntites("This string has special chars < & >");
// -> "This string has special chars < & >"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…