Skip to content

Instantly share code, notes, and snippets.

@padolsey
Last active February 21, 2024 11:49
Show Gist options
  • Save padolsey/cdb25c323a31ee1380a6 to your computer and use it in GitHub Desktop.
Save padolsey/cdb25c323a31ee1380a6 to your computer and use it in GitHub Desktop.
// context: https://twitter.com/codepo8/status/572863924887945216
function fuzzysearch(query, text) {
// Build a regex, then test text against it:
return RegExp(
query
// Escape any special regex characters:
.replace(/[.*+?^${}()|[\]\/\\]/g, '\\$&')
// Any escaped or non-escaped character can be followed by
// any number of other characters (.*):
.replace(/\\?./g, '$&.*')
).test(text);
}
fuzzysearch('twl', 'cartwheel') // <- true
fuzzysearch('cart', 'cartwheel') // <- true
fuzzysearch('cw', 'cartwheel') // <- true
fuzzysearch('ee', 'cartwheel') // <- true
fuzzysearch('art', 'cartwheel') // <- true
fuzzysearch('eeel', 'cartwheel') // <- false
fuzzysearch('dog', 'cartwheel') // <- false
fuzzysearch('[]', '[....]') // <- true
@ryanseddon
Copy link

Neat, you could just do \W that matches all the characters that need escaping:

function fuzzysearch(query, text) {
// Build a regex, then test text against it:
return RegExp(
  query
    // Escape any special regex characters:
    .replace(/\W/g, '\\$&')
    // Any escaped or non-escaped character can be followed by
    // any number of other characters (.*):
    .replace(/\\?./g, '$&.*')
  ).test(text);
} 

@padolsey
Copy link
Author

padolsey commented Mar 4, 2015

@ryanseddon, wouldn't that over-compensate by escaping even non special characters? (Am now wondering if that's even a problem, or if the escape would be ignored/redundant in those cases)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment