2011-12-08 5 views
2

次の問題が発生した場合:置換は期待通りに機能しますが、すべての結果が最初の検索に置き換えられます。 (コード例)。JS/RegExpを複数回置き換えた場合

target =強調表示される文字列を含む入力フィールド。 newCityString = htmlコード、交換が

/** 
* Highlighting for Search results (just demo) 
* TODO: This needs some work to replace the case-correct texts 
*/ 
search = new RegExp($(target).val() , 'gi'); 
matches = search.exec(newCityString); 
for(match in matches) { 
    _this = new RegExp(matches[ match ], 'gi'); 
    newCityString = newCityString.replace( 
     _this, 
     ('<span class="hl" style="background-color:yellow">' + matches[ match ] + '</span>') 
    ); 
}; 

を実行する必要があります。例:

は「フィン」を検索「findlingは細かい魚を見つけ、」だろう「Findlingは細かい魚が見つかりました」。

これは、場合によっては大文字化が間違っていることを意味します。間違いはどこですか?

答えて

-1

用途:

search = new RegExp($(target).val() , 'gi'); 
newCityString = newCityString.replace(search,function(substr){ 
    return '<span class="hl" style="background-color:yellow">' + substr + '</span>'; 
}); 
+0

Whew。それは速く、楽しく、そして大丈夫でした。ありがとう! – campino2k

0

これを試してみてください:

search = new RegExp($(target).val(), 'gi'); 
newCityString = newCityString.replace(search, function(match) { 
    return '<span class="hl" style="background-color:yellow">' + match + '</span>'; 
}); 

Hereは、作業コードです。