From fd37a268aaacecf22d3f3adc2cb1fe8e734a485c Mon Sep 17 00:00:00 2001 From: Howard Yeend Date: Mon, 30 May 2016 23:48:33 +0100 Subject: [PATCH] hoist exact matches to top of autocomplete suggestions --- src/jquery.autocomplete.js | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/jquery.autocomplete.js b/src/jquery.autocomplete.js index bd933ce9..6820f988 100644 --- a/src/jquery.autocomplete.js +++ b/src/jquery.autocomplete.js @@ -530,9 +530,32 @@ return filter(suggestion, query, queryLowerCase); }) }; - + + function wholeWordMatch(suggestion) { + return (suggestion.split(/\b/).indexOf(queryLowerCase) >= 0); + } + + function preferExactMatches(a, b) { + var sa = a.value.toLowerCase(); + var aWhole = wholeWordMatch(sa); + var sb = b.value.toLowerCase(); + var bWhole = wholeWordMatch(sb); + if (aWhole && bWhole) { + if (sa === queryLowerCase && sb === queryLowerCase) { + return 0; + } + return (sa === queryLowerCase) ? -1 : 1; + } + if (aWhole) { + return -1; + } + if (bWhole) { + return 1; + } + return 0; + } if (limit && data.suggestions.length > limit) { - data.suggestions = data.suggestions.slice(0, limit); + data.suggestions = data.suggestions.sort(preferExactMatches).slice(0, limit); } return data;