Last active
February 21, 2024 11:49
-
-
Save padolsey/cdb25c323a31ee1380a6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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)