【问题标题】:regex javascript with case insensitive flag 'i' and global wont work带有不区分大小写标志'i'和全局的正则表达式javascript不起作用
【发布时间】:2019-08-18 06:24:57
【问题描述】:

我正在研究一种方法来突出显示在字符串中找到的查询文本,这个想法是为找到的每个匹配项添加粗体标记。问题是当我尝试用 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') =&gt; is &lt;b&gt;this&lt;/b&gt; &lt;b&gt;this&lt;/b&gt;有效!

highlight(' is THIS','this') =&gt; is THIS没有

【问题讨论】:

  • indexOf() 不区分大小写吗?
  • 除此之外,您还有另一个问题,THIS 被转换为 this
  • 是的,这个问题现在没有解决,但如果你有解决方案,它仍然是一个问题,请让我现在谢谢

标签: javascript regex string regexp-replace


【解决方案1】:

试试这样的:

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

【讨论】:

  • 它工作得很好,谢谢,它不能用这个代替 THIS。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-18
  • 1970-01-01
  • 2011-04-25
  • 1970-01-01
  • 1970-01-01
  • 2011-04-22
相关资源
最近更新 更多