【问题标题】:Replace all text matched except in alt or href attribute替换所有匹配的文本,除了 alt 或 href 属性
【发布时间】:2013-03-28 15:57:05
【问题描述】:

我想用另一个文本替换所有匹配的文本,但如果该文本在althref 属性中,我不想替换。 示例:

<p>Hello world!</p>
<p><img src="hello.jpg" alt="Hello"/></p>
Hello

我的代码:

var replacepattern = new RegExp('Hello', 'gi');
newcontent = newcontent.replace(replacepattern, function(match, contents, offset, s) {
var link = 'demo.com'
    index++;
    if (link != '') {
        return '<a href="' + link + '">' + match + '</a>';
    } else {
        return match;
    }
});

它仅适用于文本。如何匹配除img srcalt 等以外的文本?

【问题讨论】:

  • 通过“等”你的意思是任何 html 属性?
  • 你必须使用 HTML 解析器,而不是正则表达式才能确定我会这么想。
  • @Blazemonger 是的,用文本替换,而不是属性
  • 嘿!我找到了解决方案。使用这个正则表达式:new RegExp('hello(?![^&lt;]*&gt;)',"gi");

标签: javascript jquery regex


【解决方案1】:

您可以使用 jQuery 本身来帮助您进行替换:

$(html)
    .contents()
    .filter(function() {
        return this.nodeType == 1 || this.nodeType == 3;
    }).each(function() {
        this.textContent = this.textContent.replace(replacepattern, 'whatever');
    });

请注意,最后一次出现的 Hello 不会被替换,因为将文本节点作为 &lt;body&gt; 的子节点在技术上是无效的。

另外,您必须修改它以在 IE node.textContent :)

更新

问题稍微复杂一些;或者也许我的想法使它变得比现在更困难。用 jQuery 替换文本节点并不是最简单的,所以需要一些纯 JS:

$('<div><p>Hello world!</p><p><img src="hello.jpg" alt="Hello"/></p>Hello</div>')
  .find('*')
  .andSelf()
  .each(function() {
    for (var i = 0, nodes = this.childNodes, n = nodes.length; i < n; ++i) {
      if (nodes[i].nodeType == 3) {
        var txt = nodes[i].textContent || nodes[i].innerText,
            newtxt = txt.replace(/Hello/g, 'Bye');
        if (txt != newtxt) {
          var txtnode = document.createTextNode(newtxt);
          this.replaceChild(txtnode, nodes[i]);
        }
      }
    }
})
  .end()
  .end()
  .appendTo('body');

【讨论】:

  • 谢谢杰克,我试过你的代码,但替换后,img 标签已被删除。有什么想法吗?
  • 尝试像这样添加一个 div 包装器:&lt;div&gt;&lt;p&gt;Hello world!&lt;/p&gt; &lt;p&gt;&lt;img src="hello.jpg" alt="Hello"/&gt;&lt;/p&gt; Hello
    我认为当节点不在同一级别时会出现问题。
  • 非常感谢@Jack!我通过使用这个正则表达式找到了一个解决方案:new RegExp('hello(?![^&lt;]*&gt;)',"gi") 但是你的方式很好。
  • 猜你喜欢
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2011-11-25
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    相关资源
    最近更新 更多