JavaScript fuzzy search

前端 未结 7 853
渐次进展
渐次进展 2020-12-24 03:39

I\'m working on this filtering thing where I have about 50-100 list items. And each items have markup like this:

  • 7条回答
    •  情话喂你
      2020-12-24 04:31

      I was looking for "fuzzy search" in javascript but haven't found a solution here, so I wrote my own function that does what I need.

      The algorithm is very simple: loop through needle letters and check if they occur in the same order in the haystack:

      String.prototype.fuzzy = function (s) {
          var hay = this.toLowerCase(), i = 0, n = -1, l;
          s = s.toLowerCase();
          for (; l = s[i++] ;) if (!~(n = hay.indexOf(l, n + 1))) return false;
          return true;
      };
      

      e.g.:

      ('a haystack with a needle').fuzzy('hay sucks');    // false
      ('a haystack with a needle').fuzzy('sack hand');    // true
      

    提交回复
    热议问题