How to implement sublime text like fuzzy search?

albertein picture albertein · Jun 4, 2013 · Viewed 7.9k times · Source

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

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

Answer

Trevor Dixon picture Trevor Dixon · Jun 4, 2013

Here's an alternate matching function. http://jsfiddle.net/trevordixon/pXzj3/4/

function match(search, text) {
    search = search.toUpperCase();
    text = text.toUpperCase();

    var j = -1; // remembers position of last found character

    // consider each search character one at a time
    for (var i = 0; i < search.length; i++) {
        var l = search[i];
        if (l == ' ') continue;     // ignore spaces

        j = text.indexOf(l, j+1);     // search for character & update position
        if (j == -1) return false;  // if it's not found, exclude this item
    }
    return true;
}

This one's faster (according to this test in Chrome), which may start to matter if you're filtering a lot of items.