简体   繁体   中英

Javascript regular expression : match 2 substrings in any order

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

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));

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() .

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/)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM