Categories
Featured Development Resources HTML/Javascript

Fuzzy String Matching JavaScript

Fuzzy string matching allows you to search through a group of strings, and organize partial matches sorted by how close your search is to the string being matched.

With fuzzy string matching the relevance is typically determined by the Levenshtein distance which refers to the number of changes it would take for one string to be equal to another.

Matching in JavaScript

There are a number of libraries available in JavaScript for performing fuzzy string matching with the most popular being Fuse.js.  

Fuse.js uses the Bitap algorithm to perform the fuzzy text matching which uses bitwise operations in for high performance and allows the Fuse to be lightweight.

Using Fuse.js

You can install Fuse.js with npm:

npm install fuse.js

Or you can embed in a page by downloading the project or using it from the Cloudflare CDN with this tag:

<script src="https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.4.6/fuse.min.js" integrity="sha512-FwWaT/y9ajd/+J06KL9Fko1jELonJNHMUTR4nGP9MSIq4ZdU2w9/OiLxn16p/zEOZkryHi3wKYsnWPuADD328Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

The great thing about Fuse.js is that it makes it extremely easy to perform a fuzzy search on an array of strings:

list = ["match me", "match you", "match"]
const fuse = new Fuse(list)
console.log(fuse.search("match"))
//[
//  { item: 'match', refIndex: 2 },
//  { item: 'match me', refIndex: 0 },
//  { item: 'match you', refIndex: 1 }
//]

You can also perform searches on full object arrays.

list = [
    {
        name: "Picard",
        rank: "Captain"
    },
    {
        name: "Kirk",
        rank: "Captain"
    },
    {
        name: "Data",
        rank: "Lieutenant-Commander"
    }
]

const options = {
    keys: ['name', 'rank']
}
const fuse = new Fuse(list, options)

console.log(fuse.search("Cap"))
//[
//    { item: { name: 'Picard', rank: 'Captain' }, refIndex: 0 },
//    { item: { name: 'Kirk', rank: 'Captain' }, refIndex: 1 }
//]

Some other nice features included allow you to score your results by the Levenshtein distance, add weighting to different keys in an object, and use search operators for more specific matching.

Conclusion

Performing a fuzzy string search in JavaScript can be complicated, but with the Fuse.js library this can be done easily and with a minimal amount of overhead.  There are other libraries out there, but Fuse.js has become the standard and is lightweight and constantly improving.

Exit mobile version