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

别来无恙 提交于 2020-01-06 08:42:06

问题


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:


Try something like this:

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


来源:https://stackoverflow.com/questions/55381390/regex-javascript-with-case-insensitive-flag-i-and-global-wont-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!