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

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

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

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

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

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

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

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

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

有任何想法吗?

使用RegExp构造函数从字符串创建RegExp对象:

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

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