在stackoverflow中有很多类似的问题和有用的答案,但我无法找到一种方式浏览器和Node.js。所以我想分享我的意见。
对于像
<
>
'
甚至汉字的html代码。
我建议使用这个功能。 (受其他答案的启发)
function decodeEntities(encodedString) {
var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
var translate = {
"nbsp":" ",
"amp" : "&",
"quot": "\"",
"lt" : "<",
"gt" : ">"
};
return encodedString.replace(translate_re, function(match, entity) {
return translate[entity];
}).replace(/&#(\d+);/gi, function(match, numStr) {
var num = parseInt(numStr, 10);
return String.fromCharCode(num);
});
}
该工具也适用于Node.js环境。
decodeEntities("哈哈 '这个'&"那个"好玩<>") //哈哈 '这个'&"那个"好玩<>
作为一个新的用户,我只有1个声望:(
我不能作出评论或回答现有员额所以这是我现在唯一能做的。
编辑1
我觉得this答案的作品比我的还要好。虽然没有人给他了投票。
https://stackoverflow.com/questions/18749591/encode-html-entities-in-javascript 这应该真的有用。确保编码是相同的 https://github.com/mathiasbynens/he – getjackx