突出显示jQuery.autocomplete的多个关键字

时间:2009-06-05 17:52:33

标签: jquery regex autocomplete highlighting

我正在使用jQuery Autocomplete plugin,但我在结果突出显示方面遇到了一些问题。找到匹配项但输入的关键字包含空格时,没有突出显示。例如:

search =“foo”,result =“foo bar”,显示=“ foo bar”

search =“foo ba”,result =“foo bar”,显示=“foo bar”

所以,我正在尝试使用自动完成功能的highlight option来修复此问题,您可以使用函数对结果执行一些自定义操作。目前我有这个:

$('.autocomplete').autocomplete('getmatch.php', {
    highlight: function(match, keywords) {
        keywords = keywords.split(' ').join('|');
        return match.replace(/(get|keywords|here)/gi,'<b>$1</b>');
    }
});

替换函数用粗体版本替换字符串中所有匹配的单词,这有效。但是,我不知道如何将关键字放入该功能。我虽然将它们分开,然后用'|'加入它们,所以“foo bar”最终会像“foo | bar”一样。但是这样的事情似乎不起作用:

return match.replace(/(keywords)/gi,'<b>$1</b>'); // seen as text, I think

return match.replace('/'+(keywords)+'/gi','<b>$1</b>'); // nothing either

有什么想法吗?

3 个答案:

答案 0 :(得分:11)

使用RegExp constructor从字符串创建 RegExp 对象:

$('.autocomplete').autocomplete('getmatch.php', {
    highlight: function(match, keywords) {
        keywords = keywords.split(' ').join('|');
        return match.replace(new RegExp("("+keywords+")", "gi"),'<b>$1</b>');
    }
});

答案 1 :(得分:1)

我调整了初始自动完成实现,因为上面的内容已经过简化,并且在术语中不会处理regEx特殊字符。

function doTheHighlight(value, term) {
    // Escape any regexy type characters so they don't bugger up the other reg ex
    term = term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1");

    // Join the terms with a pipe as an 'OR'
    term = term.split(' ').join('|');

    return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
}

答案 2 :(得分:0)

您的函数应使用此签名:function(value,term)。价值&amp;术语将由自动完成插件填充,并具有您需要的值。

相关问题