Javascript 粗体匹配搜索文本
我正在编写一个自定义控件,其中包括一个文本框输入和它下面的无序项列表。当用户在文本框中键入时,我希望列表中匹配的文本以粗体显示(用Javascript 粗体匹配搜索文本,javascript,jquery,regex,Javascript,Jquery,Regex,我正在编写一个自定义控件,其中包括一个文本框输入和它下面的无序项列表。当用户在文本框中键入时,我希望列表中匹配的文本以粗体显示(用标记包装) //我使用keyup,因此该值考虑最后一次击键。 $('#filterList').keyup(函数(){ var$this=$(this); //清除最后一个函数 clearTimeout($this.data('timer')); //如果没有其他击键,则在400ms后运行该函数 $this.data('timer',setTimeout(functi
标记包装)
//我使用keyup,因此该值考虑最后一次击键。
$('#filterList').keyup(函数(){
var$this=$(this);
//清除最后一个函数
clearTimeout($this.data('timer'));
//如果没有其他击键,则在400ms后运行该函数
$this.data('timer',setTimeout(function()){
var searchString=$this.val();
$('li')。每个(函数(){
//删除旧的强标签。
$(this.find('strong').replaceWith(function(){
返回$(this.html();
});
//问题就在这里……很接近,但不完全是这样。
$(this.html($(this.html().replace)(新的RegExp(searchString,“ig”),“”+searchString+”);
});
}, 400));
});
我遇到的问题是我希望搜索不区分大小写。我能够适当地匹配文本,但是替换它并保持原来的大小写是一个挑战。另外,我不知道我对用用户的输入创建正则表达式的感觉如何
请给我一些建议!提前谢谢你 考虑使用,您应该在几分钟内启动并运行
至于替换,您可以使用
'$&'
-$&
将添加正则表达式匹配的全文。在这种情况下,这就是你要找的。工作示例:元素LI
中的数据是什么样子的?它只包含纯文本吗?谢谢Kobi,$&正是我想要的。突出显示插件也很酷。
//I use keyup so the value takes in to account the last keystroke.
$('#filterList').keyup(function() {
var $this = $(this);
//Clears the last function
clearTimeout($this.data('timer'));
//Runs the function after 400ms if no other keystrokes have taken place
$this.data('timer', setTimeout(function() {
var searchString = $this.val();
$('li').each(function() {
//Remove old strong tags.
$(this).find('strong').replaceWith(function() {
return $(this).html();
});
//Here lies the issue... its close, but not quite there.
$(this).html($(this).html().replace(new RegExp(searchString, "ig"), '<strong>'+searchString+'</strong>'));
});
}, 400));
});