var str = 'let us pretend that this is a blog about gardening&cooking; here's an apostrophe & ampersand just for fun.';
这是我正在操作的字符串。 所需的最终结果是:"let us pretend that this is a blog about gardening&cooking; here's an apostrophe & ampersand just for fun."
console.log('Before: ' + str);
str = str.replace(/&(?:#x?)?[0-9a-z]+;?/gi, function(m){
var d = document.createElement('div');
console.log(m);
d.innerHTML = m.replace(/&/, '&');
console.log(d.innerHTML + '|' + d.textContent);
return !!d.textContent.match(m.replace(/&/, '&')[0]) ? m : d.textContent;
});
console.log('After: ' + str);
问题是HTML不支持XML的'
为避免此问题,您应该使用'
而不是'
有关更多信息,请查看此帖子:
为什么不应该使用'
来转义单引号?
这应该可以做你想要的:
str.replace(/&([#x]d+;|[a-z]+;)/g, "&$1")
或者,积极展望:
str.replace(/&(?=[#x]d+;|[a-z]+;)/g, "&")
我认为你不需要任何HTML2text en-/decodeding。