2013-03-28 40 views
0

我想替換另一個文本的所有匹配的文本匹配的所有文字,但我不想更換,如果該文本是在althref屬性。 例子:更換除ALT或href屬性

<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等之外的文字?

+0

「等」你的意思是任何html屬性? – Blazemonger

+0

你將不得不使用HTML解析器,而不是正則表達式來真正確定我會這麼想。 – thatidiotguy

+0

@Blazemonger是的,在文本中替換,而不是屬性 –

回答

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'); 
+0

感謝傑克,我想你的代碼,但更換後,img標籤已被刪除。任何想法? –

+0

@AnhTú不確定,因爲它的功能[這裏](http://jsbin.com/uvuvec/2/)。 –

+0

嘗試添加一個div包裝,像這樣: '

Hello world!

Hello

Hello'
我覺得問題發生時,節點不在同一級別。 –