Skip to content

Instantly share code, notes, and snippets.

@padolsey
Last active Apr 30, 2016
Embed
What would you like to do?
// 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

ryanseddon commented Mar 4, 2015

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