Regex - match multiple unordered words in a string

I have a list of names and I'm looking to filter the list to return names containing both the last and first names.

Say I'm looking for "Joe Doe"

I have current regex (?:^|\s)Joe|(?:^|\s)Doe

It works, but it returns all rows containing Joe or Doe. I would like it to match names containing only both names, and it could be either "Doe Joe" or "Joe Doe"

+4
source share
1 answer

This view-based regular expression should work:

/(?=.*?\bJoe\b)(?=.*?\bDoe\b).*/i

Testing:

/(?=.*?\bJoe\b)(?=.*?\bDoe\b).*/.test('Joe Doe'); // true
/(?=.*?\bJoe\b)(?=.*?\bDoe\b).*/.test('Doe Joe'); // true
+7
source

All Articles