JQuery UI Autocomplete use startsWith

autocompletejqueryjquery-ui

I'm using the jQuery UI Autocomplete with a local datasource (source: myArray). I want the autocomplete to propose only the results that start with the string entered instead of the default case-insensitive contains search. Is there a simple solution for this or do I have to provide my custom search/source callback?

Best Answer

See this:

Match start word:

http://blog.miroslavpopovic.com/jqueryui-autocomplete-filter-words-starting-with-term

He overrides the autocomplete filter method. I use this and it works well.

// Overrides the default autocomplete filter function to search only from the beginning of the string
$.ui.autocomplete.filter = function (array, term) {
    var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(term), "i");
    return $.grep(array, function (value) {
        return matcher.test(value.label || value.value || value);
    });
};

Match word:

Match startsWith of any word in the string.

e.g. "LHR london" is matched by "london"

var matcher = new RegExp("\\b" + $.ui.autocomplete.escapeRegex(term), "i");

\b assert position at a word boundary (^\w|\w$|\W\w|\w\W)