albertein albertein - 2 months ago 24
Javascript Question

How to implement sublime text like fuzzy search?

How can i implement a sublime-like fuzzy search on select2?

Example, typing "sta jav sub" would match "Stackoverflow javascript sublime like"

Answer

select2 allows you to implement your own "matcher" functions (as seen on their docs), using that and some regexp you can do something like:

$("#element").select2({
    matcher: function(term, text, opt) {
        //We call to uppercase to do a case insensitive match
        //We replace every group of whitespace characters with a .+
        //matching any number of characters
        return text.toUpperCase().match(term.toUpperCase().replace(/\s+/g, '.+'));
    }
});

A matcher function is invoked against every select2 list element when filtering / searching the list, you could implement any kind of custom search using that.