首页 > 解决方案 > 带有不区分大小写标志'i'和全局的正则表达式javascript不起作用

问题描述

我正在研究突出显示在字符串中找到的查询文本的方法,这个想法是为找到的每个匹配项添加粗体标记。问题是当我尝试用 g 替换所有出现的查询文本并且 i 标记它没有这样做时,它看起来像是忽略了 i 标记。

这是功能:

highlight  =  function(text,q){
        if (text.indexOf(q) != -1) {
            text = text.replace(new RegExp("\\b".concat(q, "\\b"), 'gi'), '<b>' + q + '</b>');
          } else{
            q = q.split(' ');
            q.forEach(function (item) {
              if (text.indexOf(item) != -1) text = text.replace(new RegExp("\\b".concat(item, "\\b"), 'gi'), '<b>' + item + '</b>');
            });
          }
             return text;
    }

随意测试它,下面是我测试的两个例子:

highlight(' is THIS this','this') => is <b>this</b> <b>this</b>. 有用 !

highlight(' is THIS','this') => is THIS.

标签: javascriptregexstringregexp-replace

解决方案


尝试这样的事情:

highlight = function(text, q) {
  return text.replace(new RegExp("\\b" + q + "\\b", 'gi'),
                      function(x) {
                        return '<b>' + x + '</b>';
                      });
}

推荐阅读