Alec
Alec

Reputation: 9078

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?

Upvotes: 5

Views: 12748

Answers (3)

Shaun
Shaun

Reputation: 11

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

Upvotes: 1

Gumbo
Gumbo

Reputation: 655785

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

Upvotes: 11

Zachary
Zachary

Reputation: 6532

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.

Upvotes: 0

Related Questions