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 Autoplete'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.
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 Autoplete'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.
Share Improve this question asked Jun 9, 2011 at 17:06 JP1971JP1971 8803 gold badges10 silver badges21 bronze badges 1- A useful piece of code might be the jQuery Highlight Plugin. Even yo aren't using jQuery you can examine the code, it was quite concise. – Kobi Commented Jun 9, 2011 at 17:21
2 Answers
Reset to default 7You 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
.
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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744954732a4603125.html
评论列表(0条)