spiel spiel - 6 months ago 17
jQuery Question

How to highlight RegEx matches with jQuery?

With the code as the base, is it possible to highlight any matching items without using an extra plug-in?

I'd like to add

style="backgorund: green;"
to the divs where the items were found, so that I can immidiately see them.

The things I've tried so far haven't been working, so I'm hoping some fresh thoughts from outside my brain will do the trick.

function finder(items){
var needed = [
/* items */
];
var re = new RegExp(needed.join("|"), "i");
return(items.match(re) != null);
}

var found = finder(document.body.innerHTML);
var output = found ? "found" : "not found";

if(output == 'found') {
//highlight found array item
}

Answer

I changed around my code a bit and solved it like this:

function finder(items){
    var needed = [
         /* items */
    ];
    var reg = new RegExp(needed.join("|"), "i");
    var found = (textToCheck.match(reg) != null);
    var foundItem = textToCheck.match(reg);
    return [found,foundItem];
}

var found = finder(document.body.innerHTML)[0];
var foundItem = finder(document.body.innerHTML)[1];

if(found === true) {
    $('div:contains('+foundItem+')').css("background", "greenyellow");
}