我正在编写一个自定义控件,其中包括一个文本框输入和下面无序的项目列表。当用户在文本框中键入时,我希望列表中匹配的文本加粗(包装在
<strong>
标签)。
//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));
});
我的问题是我希望搜索
不区分大小写
. 我能够适当地匹配文本,但替换文本并保留原来的大小写正成为一个挑战。另外,我不知道如何从用户的输入中创建正则表达式。
请提出建议!提前谢谢!