Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 400
spiel Avatar asked Dec 21 '12 12:12

spiel


People also ask

How to highlight text using regular expressions in jQuery?

Just another text highlighting jQuery plugin that enables you to highlight any strings within a specific container element using Regular expressions. 1. Download and place the main JavaScript file jquery.highlight.js after jQuery. 2. Highlight numbers using Regex. 3. Highlight characters in the HTML table. 4.

How to highlight any string within a specific container element using regular expression?

Just another text highlighting jQuery plugin that enables you to highlight any strings within a specific container element using Regular expressions. 1. Download and place the main JavaScript file jquery.highlight.js after jQuery.

What are regex selectors in jQuery?

jQuery RegEx Examples to use with .match () This is a reference post for some common RegExp ( regular expressions) selectors that can be used with the jQuery.match () function. This is very handy for finding pretty much anything inside your web page text and then doing something neat with it. Also handy for validation on forms.

Why use regular expressions with jQuery?

Combined with jQuery, it allows you to ensure that data sent to the server matches all of your requirements. In this post I have included several example regular expressions that we have used in our web design projects for validating form input.


2 Answers

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.

like image 135
mingos Avatar answered Oct 04 '22 04:10

mingos


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/

like image 24
Pablo Avatar answered Oct 04 '22 05:10

Pablo