Skip to content

Instantly share code, notes, and snippets.

@samknight
Created February 7, 2014 14:39
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save samknight/8863745 to your computer and use it in GitHub Desktop.
Save samknight/8863745 to your computer and use it in GitHub Desktop.
Fuzzy Regex match
// This will allow unordered search terms to match relevant string
// e.g. Really Long String will be matched by
// - long string
// - long really
// - all ring
// ..etc
// I have used this anonymous function to override the matcher function in select2
function(term, text) {
// Build Regex String
var matchTerm = '.*';
// Split all the search terms
var terms = term.split(" ");
for(var i = 0; i < terms.length; i++) {
matchTerm += '(?=.*' + terms[i] + '.*)';
};
matchTerm += '.*';
// Convert to Regex
// => /.*(?=.*TERM1.*)(?=.*TERM2.*).*/
var matchRegex = new RegExp(matchTerm.toUpperCase());
return text.toUpperCase().match(matchRegex);
}
@gregpardo
Copy link

Fyi I had to sanitize the term first or you can get an invalid regex.

term = term.replace(/\W/g, ''); // strip non alpha numeric

@jacobjuul
Copy link

@gregpardo if you still want to include non alpha numeric chars and not break it do this

term.replace(/(\W)/g, '\\$1')

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