Regular Expressions: Positive and Negative Lookahead?

In the example let password = "abc123"; let checkPass = /(?=\w{3,6})(?=\D*\d)/; checkPass.test(password); // Returns true , is checkPass going to check both the lookaheads while trying to match abc123 or one of them?

It will check both of them, I believe.
It checks (?=\w{3,6}) first, which looks for a string that has between 3 and 6 characters.
Then it checks (?=\D*\d), which looks for at least one number in the string.

Both must be true for the regex to pass. "abcdef" would fail, because it has 6 characters but does not have at least one number.

2 Likes

it wouldn’t fail instead, as the test method will return true if part of the string match the pattern. It needs to be specified if you want to match the whole string.


I’m showing it returns false. Is there something I’m not seeing?

there is not a number, so it is failing for that reason
but for example the string "abcdefghjidashgkfadhlk657" will give true even if the string is much longer than indicated for reason stated above

I see! Did not even think of that.
Thanks for the explanation! :slight_smile:

So to conclude, only one of the lookaheads?