【问题标题】:Why does this regex/DOM character entity tester return `undefined`?为什么这个正则表达式/DOM 字符实体测试器返回“未定义”?
【发布时间】: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


【解决方案1】:

问题是 HTML 不支持 XML 的 ' 为避免此问题,您应该使用 ' 而不是 '

更多信息请看这篇文章:

Why shouldn't ' be used to escape single quotes?

【讨论】:

  • 这绝对不是问题。包含‘’的部分工作得很好,正是我想要的方式。不工作的是&
  • 好吧,也许你只需要像这样使用更简单的函数:str = str.replace(/&/gi, function(m){ console.log(m); return m.replace (/&/, '&'); });
【解决方案2】:

这应该做你想做的:

str.replace(/&([#x]\d+;|[a-z]+;)/g, "&$1")

或者,积极的前瞻:

str.replace(/&(?=[#x]\d+;|[a-z]+;)/g, "&")

我认为您不需要任何 HTML2text 编码/解码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-25
    • 2015-02-07
    • 2019-04-20
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    相关资源
    最近更新 更多