代码之家  ›  专栏  ›  技术社区  ›  John Strickler

粗体匹配的搜索文本

  •  3
  • John Strickler  · 技术社区  · 15 年前

    我正在编写一个自定义控件,其中包括一个文本框输入和下面无序的项目列表。当用户在文本框中键入时,我希望列表中匹配的文本加粗(包装在 <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 回复  |  直到 15 年前
        1
  •  3
  •   Kobi    15 年前

    考虑使用 jQuery Highlight Plugin ,您应该在几分钟后就可以开始运行了。

    至于更换,您可以使用 '<strong>$&</strong>' - $& 将添加regex匹配的全文。在这种情况下,这就是你要找的。工作示例: http://jsfiddle.net/kobi/cKVPY/