Created
February 7, 2014 14:39
-
-
Save samknight/8863745 to your computer and use it in GitHub Desktop.
Fuzzy Regex match
This file contains hidden or 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
// 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 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
Fyi I had to sanitize the term first or you can get an invalid regex.