Skip to content

Instantly share code, notes, and snippets.

@chinghanho
Forked from dtjm/fuzzy_string_match.js
Created May 13, 2018 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chinghanho/eb0e04ad7b745546036e5908992f8992 to your computer and use it in GitHub Desktop.
Save chinghanho/eb0e04ad7b745546036e5908992f8992 to your computer and use it in GitHub Desktop.
Fuzzy string matching function for JavaScript
// Fuzzy matching algorithm
var fuzzyMatch = function(needle, haystack) {
if(needle === "" || haystack === "") return true;
needle = needle.toLowerCase().replace(/ /g, "");
haystack = haystack.toLowerCase();
// All characters in needle must be present in haystack
var j = 0; // haystack position
for(var i = 0; i < needle.length; i++) {
// Go down the haystack until we find the current needle character
while(needle[i] !== haystack[j]) {
j++;
// If we reached the end of the haystack, then this is not a match
if(j === haystack.length) {
return false;
}
}
// Here, needle character is same as haystack character
//console.log(needle + ":" + i + " === " + haystack + ":" + j);
}
// At this point, we have matched every single letter in the needle without returning false
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment