regex javascript with case insensitive flag 'i

2019-08-17 17:34发布

I working on method to highlight the query text found in a string the idea is to add bold marker to each occurrence found. the problem is when i try to replace all occurrence of the query text with g and i flag it doesn't do it, it looks like it ignore the i flag .

this is the function :

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

feel free to test it ,below is tow example that I tested with :

highlight(' is THIS this','this') => is <b>this</b> <b>this</b> . it works !

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

1条回答
祖国的老花朵
2楼-- · 2019-08-17 18:16

Try something like this:

highlight = function(text, q) {
  return text.replace(new RegExp("\\b" + q + "\\b", 'gi'),
                      function(x) {
                        return '<b>' + x + '</b>';
                      });
}
查看更多
登录 后发表回答