Highlight multiple keywords for jQuery.autocomplete

落花浮王杯 提交于 2019-12-05 00:47:41

问题


I'm using the jQuery Autocomplete plugin, but I'm having some problems with the result highlighting. When a match is found, but the entered keyword contains spaces, there's no highlighting. Example:

search = "foo", result = "foo bar", displayed = "foo bar"

search = "foo ba", result = "foo bar", displayed = "foo bar"

So, I'm trying to fix this using the highlight option of the autocomplete function where you can use a function to do some custom stuff with the results. Currently I have this:

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

The replace function replaces all the matched words in the string with a bold version, that works. However, I don't know how to get the keywords into that function. I though I'd split them, and then join them with a '|', so "foo bar" ends up like "foo|bar". But something like this doesn't seem to work:

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

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

Any ideas?


回答1:


Use the RegExp constructor to create a RegExp object from a string:

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



回答2:


I tweaked the initial autocomplete implementation as the above is simplified and won't deal with regEx special characters in the term.

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>");
}



回答3:


Your function should use this signature: function(value, term). The value & term will be populated by the autocomplete plug-in and have the values you need.



来源:https://stackoverflow.com/questions/957207/highlight-multiple-keywords-for-jquery-autocomplete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!