2011-12-08 56 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是工作代码。