Make Javascript regular expression case insensitive

前端 未结 4 1950
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-01 06:08

I\'m using a jquery function I found to find words in a div and highlight them. I\'m using this along with a search tool so the case is not always going to match the words

相关标签:
4条回答
  • 2021-01-01 06:47

    Just add the 'i' flag.

    pattern = new RegExp('(>[^<.]*)(' + what + ')([^<.]*)','gi')
    
    0 讨论(0)
  • 2021-01-01 06:49
    pattern = new RegExp('(>[^<.]*)(' + what + ')([^<.]*)','gi')
    

    add the 'i' flag to make it case insensitive

    0 讨论(0)
  • 2021-01-01 06:50
    $.fn.highlight = function(what,spanClass) {
    return this.each(function(){
        var container = this,
            content = container.innerHTML,
            pattern = new RegExp('(>[^<.]*)(' + what + ')([^<.]*)','gi'),
            replaceWith = '$1<span ' + ( spanClass ? 'class="' + spanClass + '"' : '' ) + '">$2</span>$3',
            highlighted = content.replace(pattern,replaceWith);
        container.innerHTML = highlighted;
    });
    

    }

    0 讨论(0)
  • 2021-01-01 06:51

    Just add "i":

    pattern = new RegExp('(>[^<.]*)(' + what + ')([^<.]*)','gi'),
    

    From MDN:

    Regular expressions have four optional flags that allow for global and case insensitive searching. To indicate a global search, use the g flag. To indicate a case-insensitive search, use the i flag. To indicate a multi-line search, use the m flag. To perform a "sticky" search, that matches starting at the current position in the target string, use the y flag. These flags can be used separately or together in any order, and are included as part of the regular expression.

    0 讨论(0)
提交回复
热议问题