Regex to match string containing two words in any order

Hi guys,

I want to search a string with two , maybe three words , maybe more … But the basic idea is this:

If I have a string like "Hello my name is Jack and this is Matt."

And I have a working regex like this: ^(?=.*\bjack\b)(?=.*\bmatt\b).*$

However, it’s hard-coded. Now when I try to create a RegExp and pass in the variables it somehow strips out the entire RegExp and I don’t know why?

(ie)
Original RegExp
var regex = /^(?=.*\bjack\b)(?=.*\bmatt\b).*$/

RegExp with vars

 var nameOne = 'jack'
 var nameTwo = 'matt'
 var regex2  = new RegExp(`^(?=.*\b${nameOne}\b)(?=.*\b${nameTwo}\b).*$`)

When I console log the two regex’s I can see the second one has stripped out some of it:

console.log(regex) // => /^(?=.*\bjack\b)(?=.*\bmatt\b).*$/`
console.log(regex2) // => /^(?=.*jack)(?=.*matt).*$/

It seems the \b chars are stripped out. How can I prevent this from happening?

A potential workaround is just to just a loop, like so:

const subject = 'One apple is better than two.';

function matchWords(subject, words) {
    return words.every(el => subject.toLowerCase().includes(el.toLowerCase()));
}

matchWords(subject, ["one","two"]);

Cool thanks! Woops!
That seems to work now :slight_smile: