2013-01-14 18 views
1

我試圖用圖像標籤替換圖像中的圖釋,只有當它不在特定的字符組內時。替換字符串中的圖釋,除非在特定的一組文本內

考慮:

var reg = /(?!<):\/(?![^<>]*>)/g, 
    string = ':/ <a href="http://blah.com">http://blah.com</a> :/', 
    result = string.replace(reg, 'IMG'); 

結果:IMG <a href="http://blah.com">httpIMG/blah.com</a> IMG

我想知道是否有忽略HTML標籤,而不是隻內<>內置換的方式。

+0

不要試圖用正則表達式分析(匹配)HTML!使用DOM! – Bergi

+0

問題在於字符串不是DOM的一部分,我不想在格式化之前添加它。我通過使用從未添加到DOM的元素來解決此問題 - 請參閱下面的答案(我不能將其標記爲答案)。 – RagglesX

回答

0

爲什麼不符合字邊界?

/\B:\/\B/ 

這將匹配:
:/
富:/條

但不是:
HTTP://
富:/條

+0

我希望能夠替換:/:/或嘿:D,所以我想暫時保持清醒,除非沒有別的辦法。 – RagglesX

1

也許這是不是最好的解決方案但如果您使用jQuery以下「oneliner」可以做的工作:

var str = ":/ <a href='http://blah.com'>http://blah.com</a> :/"; 

$("<div />", { html : str }).contents().each(function() { 
    if (this.nodeType === 3) 
     this.nodeValue = this.nodeValue.replace(/:\//g, "IMG"); 
}).end().html(); 

DEMO:http://jsfiddle.net/Hfnje/

+0

我嘗試了這一點,雖然該示例按預期工作,但我實際上希望「IMG」成爲HTML標記。不幸的是,僅僅用HTML代替它不起作用,因爲nodeType不會改變;它看起來應該是<和>而不是< or >。不過謝謝你的建議,也許我可以用它做點什麼! – RagglesX

0

與@VisioN的幫助下,我設法想出這個:

message = 
    $('<div />', html: message).contents().each(-> 
    if @nodeType is 3 
     for replacement, emoticons of self.emoticons 
     for emoticon in emoticons 
      @nodeValue = @nodeValue.replace new RegExp(emoticon, 'g'), 
      $('<span />', class:'emoticon ' + replacement, title: emoticon)[0].outerHTML 

     $(@).replaceWith @nodeValue 
).end().html() 

這不是很漂亮,但它的工作。