6

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 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;
    });
}

4 Answers 4

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

add the 'i' flag to make it case insensitive

Sign up to request clarification or add additional context in comments.

Comments

0

Just add the 'i' flag.

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

Comments

0
$.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;
});

}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.