How to implement sublime text like fuzzy search?

前端 未结 7 2019
小蘑菇
小蘑菇 2020-12-24 12:41

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

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

7条回答
  •  滥情空心
    2020-12-24 13:14

    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.

提交回复
热议问题