-
-
Save chinghanho/eb0e04ad7b745546036e5908992f8992 to your computer and use it in GitHub Desktop.
Fuzzy string matching function for JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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