How to implement sublime text like fuzzy search?

前端 未结 7 2002
小蘑菇
小蘑菇 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:08

    had difficulties with new select2, here what worked

     $("#foo").select2({
       matcher: matcher
     });
    
    function matcher(params, data) {
      // return all opts if seachbox is empty
      if(!params.term) {
        return data;
      } else if(data) {
        var term = params.term.toUpperCase();
        var option = data.text.toUpperCase();
        var j = -1; // remembers position of last found character
    
        // consider each search character one at a time
        for (var i = 0; i < term.length; i++) {
          var l = term[i];
          if (l == ' ') continue;     // ignore spaces
    
          j = option.indexOf(l, j+1);     // search for character & update position
          if (j == -1) return false;  // if it's not found, exclude this item
        }
        return data; // return option
      }
    }
    

提交回复
热议问题