I’m trying to build a search feature for a project which narrows down items based on a user search input and if it matches the keywords listed against items. For this, I’m saving the item keywords in a data attribute and matching the query with these keywords using a RegExp pattern.
I’m currently using this expression, which I know is not correct and need your help on that:
new RegExp('\\b(' + query + ')', 'gi'))) where query is | separated values of the query entered by the user (e.g. \\b(meat|pasta|dinner)). This returns me a match even if there is only 1 match, say for example – meat
Just to throw some context, here’s a small example:
If a user types: meat pasta dinner it should list all items which have ALL the 3 keywords listed against them i.e. meat pasta and dinner. These are independent of the order they’re typed in.
Can you help me with an expression which will match ALL words in a query, in any order?
You can achieve this will lookahead assertions
See it here on Regexr
(?=.*\bmeat\b)is a positive lookahead assertion, that ensures that\bmeat\bis somewhere in the string. Same for the other keywords and the.+is then actually matching the whole string, but only if the assertions are true.But it will match also on “dinner meat Foobar pasta”