2017-02-02 40 views
1

我在jquery中使用了一個帶有replace的正則表達式,它可以找到定義中的所有單詞,並用鏈接到該單詞頁面的自定義鏈接替換它們。我的問題是,在我的一些定義中定義了一個<a>鏈接。忽略jQuery中的字符串用字邊界替換正則表達式

實施例正確的輸入

This is a definition of a word in my database <a href="http://www.example.com">[source]</a>. 

實施例正確的輸出

This is a <a href="/dictionary/word/definition">definition</a> of a <a href="/dictionary/word/word">word</a> in my <a href="/dictionary/word/database">database</a> <a href="http://www.example.com">[source]</a>. 

我使用的停止詞的陣列,因此不會自定義鏈路適用於這些類型的單詞的類似

var stopwords = ["a", "about", "above", "across", "after",... 

問題是當我檢查頁面的HTML時,它會像這樣在定義中更改該鏈接的href

This is a <a href="/dictionary/word/definition">definition</a> of a <a href="/dictionary/word/word">word</a> in my <a href="/dictionary/word/database">database</a> <a href="/dictionary/word/source">[source]</a>. 

它正在改變http://www.example.com/dictionary/word/souce我不想做的事。有沒有什麼辦法可以保留這個[源]鏈接,但對所有其他單詞都是正常工作的?

$('.definition').html(function() { 
    return $(this).text().replace(/\b[\w-]+\b/g, function(m){ 
     if ($.inArray(m.toLowerCase(), stopwords) === -1) { 
      return ' <a href="/dictionary/word/' + m.toLowerCase() + '/">' + m + '</a>'; 
     } else { 
      return " "+m; 
     } 
    }); 
}) 
+0

什麼是停用詞 –

+0

我在詢問你的名單中的單詞 –

+0

我做了編輯 –

回答

0

使用唯一的正則表達式的解決方案可能不適合處理DOM字符串,而不是你可以不喜歡做的目標元素

var stopwords = ['this', 'is', 'a', 'of', 'in', 'my', '', '[source]', '', '', '', '', '', '']; 
 

 
$('.definition').contents().each(function process() { 
 
    //console.log(this, this.nodeType); 
 
    if (this.nodeType == Node.TEXT_NODE) { 
 
    var content = $(this).text().replace(/\b[\w-]+\b/g, function(m) { 
 
     if ($.inArray(m.toLowerCase(), stopwords) === -1) { 
 
     return ' <a href="/dictionary/word/' + m.toLowerCase() + '/">' + m + '</a>'; 
 
     } else { 
 
     return " " + m; 
 
     } 
 
    }); 
 

 
    $(this).replaceWith(content); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="definition"> 
 
    This is a definition of a word in my database <a href="http://www.example.com">[source]</a>. 
 
</div>

內僅更換文本節點