spiel
spiel

Reputation: 347

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
}

Upvotes: 6

Views: 5116

Answers (4)

dude
dude

Reputation: 6086

Using innerHTML is evil as it will replace events and triggers generation of the DOM over and over again. I'd recommend to use an existing plugin as there are more pitfalls you will ran into. Have a look at mark.js to highlight custom regular expressions.

Upvotes: 1

spiel
spiel

Reputation: 347

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

Upvotes: -1

Pablo
Pablo

Reputation: 1093

You can try something with a replace()

for (var i = 0; i < needed.length; i++) {
    var word = needed[i];
    document.body.innerHTML = document.body.innerHTML.replace(word, '<span style="background: #00ff00">' + word + '</span>');
}

Try it here: http://jsfiddle.net/4kjuw/

Upvotes: 1

mingos
mingos

Reputation: 24542

Why reinvent the wheel? There are ready solutions for this. Try this plugin, for instance. Here's the source code for the plugin. It's literally a few lines of code, so if you really feel like writing your own highlighting engine, you can analyse it to see how the highlighting is performed.

Upvotes: 1

Related Questions