Search code examples
javascriptregexstringregexp-replace

regex javascript with case insensitive flag 'i' and global wont work


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


Solution

  • Try something like this:

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