Make Javascript case-insensitive regular expression

I am using a jquery function I found to find words in a div and highlight them. I use this in conjunction with a search tool so the case won't always match the words exactly. How can I convert this to make it case insensitive?

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

      

+3


source to share


4 answers


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

      



add flag 'i' to make case insensitive

+16


source


Just add the 'i' flag.



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

      

0


source


$.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


source


Just add "i":

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

      

From MDN :

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

0


source







All Articles