Reputation: 2463
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
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
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
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
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