Fuzzy Search Algorithm in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript String function that takes in a search string can loosely checks for the search string in the string it is used with.

The function should take this criterion into consideration: It should loop through the search query letters and check if they occur in the same order in the string.

For example −

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


const fuzzySearch = function (query) {
   const str = this.toLowerCase();
   let i = 0, n = -1, l;
   query = query.toLowerCase();
   for (; l = query[i++] ;){
      if (!~(n = str.indexOf(l, n + 1))){
         return false;
   return true;
String.prototype.fuzzySearch = fuzzySearch;
console.log(('a haystack with a needle').fuzzySearch('hay sucks'));
console.log(('a haystack with a needle').fuzzySearch('sack hand'));


This will produce the following output −

Published on 25-Nov-2020 09:24:47