0

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

<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 src等之外的文本alt

4

1 回答 1

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 < 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');
于 2013-03-28T16:13:42.260 回答