Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: highlight substring keeping original case but searching in case insensitive mode

I'm trying to write a "suggestion search box" and I cannot find a solution that allows to highlight a substring with javascript keeping the original case.

For example if I search for "ca" I search server side in a case insensitive mode and I have the following results:

Calculator

calendar

ESCAPE

I would like to view the search string in all the previous words, so the result should be:

Calculator

calendar

ESCAPE

I tried with the following code:

var reg = new RegExp(querystr, 'gi'); var final_str = 'foo ' + result.replace(reg, '<b>'+querystr+'</b>'); $('#'+id).html(final_str); 

But obviously in this way I loose the original case!

Is there a way to solve this problem?

like image 242
Giovanni Di Milia Avatar asked Jul 20 '10 21:07

Giovanni Di Milia


2 Answers

Use a function for the second argument for .replace() that returns the actual matched string with the concatenated tags.

Try it out: http://jsfiddle.net/4sGLL/

reg = new RegExp(querystr, 'gi');        // The str parameter references the matched string        //    --------------------------------------v final_str = 'foo ' + result.replace(reg, function(str) {return '<b>'+str+'</b>'}); $('#' + id).html(final_str);​ 

JSFiddle Example with Input: https://jsfiddle.net/pawmbude/

like image 79
user113716 Avatar answered Sep 20 '22 16:09

user113716


ES6 version

const highlight = (needle, haystack) =>   haystack.replace(       new RegExp(needle, 'gi'),       (str) => `<strong>${str}</strong>`   ); 
like image 33
serby Avatar answered Sep 19 '22 16:09

serby