Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight all occurrences of string - case insensitive

On this page I want to search for a word in the text and highlight all occurrences. If, for example, I look for "front end" than I want all occurrences of "Front end" to be highlighted. With the code below I do highlight them but the occurrences's upper case character is also replaced. Can you fix this? here's my code:

this makes jQuery contains case insensitive

$.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});

and this is the code that highlights by replacing

$('input[value="Zoeken"]').click(function(){
    $('.section').html(function (i, str) {
        yellowspan = new RegExp('<span style="background-color: #FFFF00">' ,"g"); 
        empty = "";
        return str.replace(yellowspan, empty);
    });

    $('.section').html(function (i, str) {
        endspan = new RegExp("</span>" ,"g"); 
        empty = "";
        return str.replace(endspan, empty);
    });

    var string = $('input[placeholder="Zoeken"]').val();                    
    $('.section:contains("' + string + '")').each(function(index, value){
        $(this).html(function (i, str) {
            simpletext = new RegExp(string,"gi"); 
            yellowtext = "<span style='background-color: #FFFF00'>" + string + "</span>";
            return str.replace(simpletext, yellowtext);
        });
    });
});

the problematic code is on the last html() function

like image 681
Konstantinos Papakonstantinou Avatar asked Dec 29 '25 07:12

Konstantinos Papakonstantinou


1 Answers

replace

simpletext = new RegExp(string,"gi"); 
yellowtext = "<span style='background-color: #FFFF00'>" + string + "</span>";
return str.replace(simpletext, yellowtext);

with

simpletext = new RegExp("(" + string + ")","gi"); 
return str.replace(simpletext, "<span style='background-color: #FFFF00'>$1</span>")

the extra parens in new Regexp() capture the value found. the $1 in str.replace inserts the captured value

like image 135
Nicolás Straub Avatar answered Dec 30 '25 21:12

Nicolás Straub



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!