I am using select2 in my website and i want the autocomplete to match only the beginning of the word. For example, if I type "CA" I want CAmeroun to appear and not "vatiCAn".
Asked
Active
Viewed 1,923 times
2 Answers
2
I figured out how to resolve this by searching in the documentation (here https://github.com/select2/select2/issues/428).
In select2 library, replace in select2.js :
matcher: function(term, text) {
return stripDiacritics(''+text).toUpperCase().indexOf(stripDiacritics(''+term).toUpperCase()) >= 0;
},
by :
matcher: function(term, text) {
if (text.toUpperCase().indexOf(term.toUpperCase()) == 0) {
return true;
}
},
And tadaaa. It works. I hope someone who is better in JS (99% of JS developers) could give a better answer or create a good patch.
Don't forget to minify your JS ;) !

Ismail H
- 4,226
- 2
- 38
- 61
-
There's also [an example for custom matchers](http://select2.github.io/examples.html#matcher) that features this exact use case. So I'd recommend that if you don't want to modify `select2.js` (you shouldn't). – Kevin Brown-Silva Jul 17 '15 at 17:52
-
The problem is that the select2 is part of a contribution module in Drupal. But i totally agree with you, I shouldn't modify select2.js ! – Ismail H Jul 20 '15 at 09:10
0
Inspired by @IsmailH answer. I've merged this code as matchCustom in the provided example, here.
And here's my modification,
function matchCustom(params, data) {
// If there are no search terms, return all of the data
if ($.trim(params.term) === '') {
return data;
}
// `params.term` should be the term that is used for searching
// `data.text` is the text that is displayed for the data object
if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
var modifiedData = $.extend({}, data, true);
// You can return modified objects from here
// This includes matching the `children` how you want in nested data sets
return modifiedData;
}
// Return `null` if the term should not be displayed
return null;
};

Nurhun
- 475
- 1
- 9
- 21