Javascript regular expression : match 2 substrings in any order

mens Source

After reading how to write a regexp in Javascript, I'm still pretty confused how to write this one...

I want to match every string containing at least one occurence of 2 substrings, in any order.

Say sub1 = "foo" and sub2 = "bar"

foo => doesn't match

bar => doesn't match

foobar => matches

barfoo => matches

foohellobar => matches

Could somebody help me with this ?

Additionnally, I'd like to exclude another substring. So it would match the strings containing the 2 substrings like before, but not containing a sub3, regardless of its order with the 2 others.

Thanks a lot

javascriptregex

Answers

answered 3 years ago bambam #1

This will work:

/.*foo.*bar|.*bar.*foo/g

.* matches 0 or many characters (where . matches any character and * stands for 0 or many)

| is regex' or operator

Generated code from regex101:

var re = /.*foo.*bar|.*bar.*foo/g; var str = 'foobar'; var m;

while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
}

DEMO

That being said, better use Oriol's answer using indexOf() or includes().

answered 3 years ago Oriol #2

You can use indexOf:

str.indexOf(sub1) > -1 && str.indexOf(sub2) > -1

Or includes in ES6:

str.includes(sub1) && str.includes(sub2)

Or if you have an array of substrings:

[sub1, sub2/*, ...*/].every(sub => str.includes(sub));

answered 3 years ago Alexey Shein #3

I would not use a complicated regex, but instead just used logical operand &&.

var param = 'foobar'; 
alert(param.match(/foo/) && param.match(/bar/) && !param.match(/zoo/));

param = 'foobarzoo'; 
alert(param.match(/foo/) && param.match(/bar/) && !param.match(/zoo/));

comments powered by Disqus