regexp logic and or
I know there are logical op开发者_如何学运维erators 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
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.
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);
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.
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);
精彩评论