I want to implement a regex matching function in javascript that matches one or more keywords in a text. Each keywords has to be found in any order. Keywords are entered by the user.
Here’s where i am at:
\b(smart.*\bwork.*|work.*\bsmart.*)
- matches
"trying to work smarter" - but not
"trying to work" or "trying to be smart"
The problem with this approach is i have to create different ordered permutations (something like that anyway) of the keyword set.
So the questions are:
- If there a simple RegEx-only way? (I.e
"\b(smart.*|work.*)<magic:all,anyorder>"what will make sure all keywords are found, and in any order) - If not – can you suggest a javascript implementation of array permutations (so that from
[1,2,3]it generates[[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]])
UPDATE
This is intended to be used for searching a set of strings (10-50 strings) on the client side (in browser).
My friend Juan’s answer will work pretty well unless the user is looking for small words that may appear in larger words. In that case you’ll need to fall back to regular expressions. You can use a hybrid approach that only uses the RE when the string is found. Something like:
Never tested, especially not the escapeRe bit.