【发布时间】:2012-09-16 04:21:11
【问题描述】:
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);
【问题讨论】:
-
您在返回的开头有
!!。我不认为这是有效的语法,如果是,我认为它会自行取消。 -
@Shmiddty
!!用于将操作数转换为布尔值。这是有效的语法,我认为它与问题无关。 -
this question 可能会给你一些答案。 HTML 编码是其中之一,您应该重复使用经过验证的解决方案,而不是尝试自行开发。
-
不...“内部”(第二个)将其转换为布尔表达式,(并且,就像你说的,将其反转),第二个重新(未)反转它。这就是想法,取消它而不需要麻烦的嵌套括号。
-
我不确定你匹配 de-
&ed 字符串的第一个字符的意义是什么,你能解释一下你的意图吗?
标签: javascript html regex dom character-entities