40

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

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
Alexander
  • 2,423
  • 4
  • 23
  • 17

4 Answers4

47

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.

Walf
  • 8,535
  • 2
  • 44
  • 59
markijbema
  • 3,985
  • 20
  • 32
  • 4
    I wouldn't call the second version hackish - on the contrary, especially if more than two conditions are involved, I find sequential lookaheads much more straightforward. – Tim Pietzcker Mar 03 '11 at 07:49
6

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);
Walf
  • 8,535
  • 2
  • 44
  • 59
5

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.

Community
  • 1
  • 1
iivel
  • 2,576
  • 22
  • 19
1

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);
Eissa Saber
  • 161
  • 1
  • 8