Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Text Highlight with jQuery

First of all, YES, I know there are many highlight jquery plugins out there, I've seen them and they made me satisfied, but now there is a question for me which I want to ask!

Why should I use a plugin which is 7kb? this should be solved with 2 lines of code...

Here is what I am doing, I'm searching in my webapp and I want to highlight matching parts, for example I enter "ab" as search query, then I will have these results loaded by Ajax into my HTML:

<div class="blah"><h3><a>Abicert</a></h3></div>
<div class="blah"><h3><a>The aboony test</a></h3></div>
<div class="blah"><h3><a>Abnormal abiba!!!</a></h3></div>

So in the above results, every "ab" should be highlighted, like:

Ab icert

ab oony test

Ab normal ab iba!!!

So, my jQuery is:

$('.blah h3 a').each(function(){
    var text = $(this).text();
    var searched_text = 'ab';
    // MY QUESTION HERE - How to highlight part of this text
});

Another thing that I need to mention is that: the User may enter "ab anotherquery" as his search query, so this should be exploded by space, and in the results every "ab" and "anotherquery" should be highlighted.

I would like to learn this, it's not a thing that I could not solve with ready plugins...

Thanks in advance

like image 218
behz4d Avatar asked Jan 31 '26 11:01

behz4d


1 Answers

Use RegExp and preg_quote (which takes care of characters used in regex).

function preg_quote( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: booeyOH
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: preg_quote("$40");
    // *     returns 1: '\$40'
    // *     example 2: preg_quote("*RRRING* Hello?");
    // *     returns 2: '\*RRRING\* Hello\?'
    // *     example 3: preg_quote("\\.+*?[^]$(){}=!<>|:");
    // *     returns 3: '\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:'

    return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
}


$('.blah h3 a').each(function(){
    var text = $(this).text();
    var searched_text = 'ab la';
    var keywords = searched_text.split(' ');
    keywords = $.map(keywords, preg_quote);
    $(this).html(text.replace(new RegExp("(" + keywords.join('|') + ")" , 'gi'), "<b>$1</b>"));
});​

This will break the search query by space and wrap each match with <b>

Demo (JSFiddle)

like image 136
Wojciech Zylinski Avatar answered Feb 02 '26 03:02

Wojciech Zylinski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!