Alexander
Alexander

Reputation: 2463

regexp logic and or

I know there are logical operators such as | "the OR operator" which can be used like this:

earth|world

I was wondering how I could check if my string contains earth AND world.

regards, alexander

Upvotes: 41

Views: 79410

Answers (4)

markijbema
markijbema

Reputation: 4055

If it contains earth AND world, it contains one after the other, so:

earth.*world|world.*earth

A shorter alternative (using extended regex syntax) would be:

/^(?=.*?earth)(?=.*?world)/

But it is not at all like an and operator. You can only do or because if only one of the words is included, there is no ordering involved. If you want to have them both, you need to indicate the order.

Upvotes: 48

Eissa Saber
Eissa Saber

Reputation: 189

you don't need & operator actually | operator does the job

let string = 'world and earth are awesome';
let regex = /world|earth/ig;

let result = string.replace(regex, '...');

console.log(string);
console.log(result);

Upvotes: 1

Walf
Walf

Reputation: 9338

do two tests, if the first fails the second doesn't execute in javascript. e.g.

var hasBoth = /earth/i.test(aString) && /world/i.test(aString);

Upvotes: 6

iivel
iivel

Reputation: 2576

This question was asked and answered here:

Regular Expressions: Is there an AND operator?

There isn't a direct "and" operator, but you can continue expression testing and ensure the second expression is also a match.

Upvotes: 5

Related Questions