2017-02-02 12 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>. 

それは私がそれをやっていけない/dictionary/word/souceからhttp://www.example.comを変えています。私はこの[ソース]リンクを保存する方法はありますか?他のすべての言葉は正常に動作しますか?

$('.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

ターゲット要素

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>

内のみテキストノードの交換を行うように代わりにあなたが何かを行うことができ、DOMの文字列を処理することは適切ではないかもしれないだけで、正規表現のソリューションを使用して
関連する問題