出现以下问题:替换按预期工作但是:所有发现都替换为第一个发现。 (以下代码示例)。
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>')
);
};
示例:
“Finding finds a fine fish”搜索“fin”将是“findling finds a fine fish”。
这意味着:在某些情况下,大小写会出错。哪里错了?
最佳答案
试试这个:
search = new RegExp($(target).val(), 'gi');
newCityString = newCityString.replace(search, function(match) {
return '<span class="hl" style="background-color:yellow">' + match + '</span>';
});
Here 是工作代码。
关于javascript - 使用 JS/RegExp 进行多次替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8433057/