Bolden匹配搜索文本

时间:2010-10-20 17:55:20

标签: javascript jquery regex

我正在编写一个自定义控件,其中包含一个文本框输入和一个无序的项目列表。当用户在文本框中键入时,我希望列表中的匹配文本加粗(包含在<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));
    });

我遇到的问题是我希望搜索不区分大小写。我能够恰当地匹配文本,但更换它并保持原始外壳正在成为一个挑战。另外,我不知道从用户的输入中创建正则表达式的感觉。

建议请!提前谢谢!

1 个答案:

答案 0 :(得分:3)

考虑使用jQuery Highlight Plugin,您应该在几分钟内启动并运行。

对于替换,您可以使用'<strong>$&</strong>' - $&添加正则表达式匹配的全文。在这种情况下,这就是你要找的东西。工作示例:http://jsfiddle.net/kobi/cKVPY/

相关问题