替换所有匹配的文本,但alt或href属性除外

时间:2013-03-28 15:57:05

标签: javascript jquery regex

我想用其他文字替换所有匹配的文字,但如果该文字位于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等文字以外的文字?

1 个答案:

答案 0 :(得分:2)

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

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

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

此外,您必须将其修改为在IE中工作&lt; 9或10;基本上浏览器应该支持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');
相关问题