【问题标题】:Multiple Replacements with JS / RegExp使用 JS / RegExp 进行多次替换
【发布时间】:2012-01-16 00:16:39
【问题描述】:

出现以下问题:替换按预期工作,但是:所有发现都替换为第一个发现。 (示例如下代码)。

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>') 
    );
};

示例:

“寻觅佳鱼”搜索“fin”将是“寻觅寻觅佳鱼”。

这意味着:在某些情况下,大小写是错误的。哪里错了?

【问题讨论】:

    标签: javascript jquery html regex


    【解决方案1】:

    用途:

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

    【讨论】:

      【解决方案2】:

      试试这个:

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

      Here 是工作代码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-04
        • 1970-01-01
        • 2021-02-12
        相关资源
        最近更新 更多