views:

112

answers:

4

Hi everybody,

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:

reg = new RegExp(querystr, 'gi');
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?

A: 

I use this jQuery plugin and it does the job. try it

http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html

hardcodecoder
A: 

I do the exact same thing.

You need to make a copy.

I store in the db a copy of the real string, in all lower case.

Then I search using a lower case version of the query string or do a case insensitive regexp.

Then use the resulting found start index in the main string, plus the length of the query string, to highlight the query string within the result.

You can not use the query string in the result since its case is not determinate. You need to highlight a portion of the original string.

Larry K
+5  A: 

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);​
patrick dw
JoostK
the __perfect solution__
Giovanni Di Milia
patrick dw
I didn't either, but I always forget the `function` syntax so I went looking for some documentation. I found this by 'accident'.
JoostK
damn, I knew mine felt like too much work...
jasongetsdown
A: 

.match() performs case insensitive matching and returns an array of the matches with case intact.

var matches = str.match(queryString),
    startHere = 0,
    nextMatch,
    resultStr ='',
    qLength = queryString.length;

for (var match in matches) {
    nextMatch = str.substr(startHere).indexOf(match);
    resultStr = resultStr + str.substr(startHere, nextMatch) + '<b>' + match + '</b>';
    startHere = nextMatch + qLength;
}
jasongetsdown