出现以下问题:替换按预期工作,但:所有发现都替换为第一个发现。(下面的代码示例)。
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>')
    );
};

例子:
“找鱼找鱼”找“鱼”就是“找鱼找鱼”。
这意味着:在某些情况下,资本化是错误的。哪里错了?

最佳答案

使用:

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

09-08 09:05