JavaScript fuzzy search

前端 未结 7 879
渐次进展
渐次进展 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:13

      Another (simple) solution. Non case-sensitive and ignores order of the letters.

      It performs a check for every letter of the search-term. If the original string contains that letter, it will count up (or down if it doesn't). Based on the ratio of matches / string-length it will return true or false.

      String.prototype.fuzzy = function(term, ratio) {
          var string = this.toLowerCase();
          var compare = term.toLowerCase();
          var matches = 0;
          if (string.indexOf(compare) > -1) return true; // covers basic partial matches
          for (var i = 0; i < compare.length; i++) {
              string.indexOf(compare[i]) > -1 ? matches += 1 : matches -=1;
          }
          return (matches/this.length >= ratio || term == "")
      };
      

      Examples:

      ("Test").fuzzy("st", 0.5) // returns true
      ("Test").fuzzy("tes", 0.8) // returns false cause ratio is too low (0.75)
      ("Test").fuzzy("stet", 1) // returns true
      ("Test").fuzzy("zzzzzest", 0.75) // returns false cause too many alien characters ("z")
      ("Test").fuzzy("es", 1) // returns true cause partial match (despite ratio being only 0.5)
      

    提交回复
    热议问题