Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight multiple keywords for jQuery.autocomplete

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?

like image 624
Alec Avatar asked Jun 05 '09 17:06

Alec


2 Answers

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>');
    }
});
like image 135
Gumbo Avatar answered Nov 15 '22 05:11

Gumbo


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>");
}
like image 34
Shaun Avatar answered Nov 15 '22 05:11

Shaun