Fuzzy Search Algorithm in JavaScript

Fuzzy search allows finding strings that match a pattern even when characters are not consecutive. In JavaScript, we can implement a fuzzy search algorithm that checks if characters from a search query appear in the same order within a target string.

How Fuzzy Search Works

The algorithm loops through each character of the search query and verifies that all characters exist in the target string in the same sequential order, though they don't need to be adjacent.

For example:

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

In the second case, 's', 'a', 'c', 'k', ' ', 'h', 'a', 'n', 'd' all appear in order within "a haystack with a needle".

Implementation

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'));
false
true

How the Algorithm Works

The function works by:

  • Converting both strings to lowercase for case-insensitive matching
  • Using indexOf() to find each query character starting from the position after the previous match
  • The bitwise NOT operator ~ converts -1 (not found) to 0 (falsy), making !~ return true when a character isn't found
  • Returning false immediately if any character breaks the sequence

Alternative Implementation

Here's a more readable version using modern JavaScript:

function fuzzySearchModern(text, query) {
    text = text.toLowerCase();
    query = query.toLowerCase();
    
    let textIndex = 0;
    
    for (let char of query) {
        const foundIndex = text.indexOf(char, textIndex);
        if (foundIndex === -1) {
            return false;
        }
        textIndex = foundIndex + 1;
    }
    
    return true;
}

console.log(fuzzySearchModern('a haystack with a needle', 'hay sucks'));
console.log(fuzzySearchModern('a haystack with a needle', 'sack hand'));
console.log(fuzzySearchModern('JavaScript', 'JScrpt'));
false
true
true

Use Cases

Fuzzy search is commonly used in:

  • Search autocomplete features
  • File and command search in IDEs
  • Filtering large datasets with approximate matching
  • User-friendly search interfaces that handle typos

Conclusion

Fuzzy search algorithms enable flexible string matching by checking character sequence order rather than exact matches. This implementation provides an efficient way to search for patterns within strings while allowing for gaps between characters.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements