Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserving case / capitalization with JavaScript replace method

I'm continuing work on a search term suggestion tool using Jquery UI. I am now working on displaying the results with the search term pattern in bold. I have implemented this functionality through patching the Autocomplete's _renderItem method. The problem I have now is that the replaced characters have the same case as those typed by the user in the input (e.g. if the user typed an "A" and the returned result was "America", the replaced text would be AmericA. Here's the code:

    var exp = new RegExp(this.term, "gi") ;
    var rep = item.label.replace( exp, "<span style='font-weight:bold;color:Black;'>"
    + this.term + "</span>");

As always, thanks in advance for any help.

like image 558
JP1971 Avatar asked Jan 19 '23 13:01

JP1971


2 Answers

You can use:

var rep = item.label.replace(exp,
                             "<span style='font-weight:bold;color:Black;'>$&</span>");

When replacing a string, $& means "the whole match", so you don't have to repeat the search term (in some cases you don't know it). In other flavors, you may use $0 or \0.
Also, remember to escape special characters in this.term.

like image 113
Kobi Avatar answered Jan 22 '23 03:01

Kobi


You can add your expression in a group by encapsulating them in parentheses

var exp = new RegExp("(" + this.term + ")", "gi") ;
var rep = item.label.replace( exp, "<span style='font-weight:bold'>$1</span>");

You can the refere to that group using $1.

See here for more details about backreferences.

like image 31
Peter Tillemans Avatar answered Jan 22 '23 01:01

Peter Tillemans