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
Example
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'));
Output
This will produce the following output −
false true