Help! Positive and Negative Lookahead

My regex is not able to match "bana12" and "abc123". What have I done wrong?

Any help would be appreciated!


let sampleWord = "astronaut";
let pwRegex = /(?=\w{5,})(?=\d{2})/; // Change this line
let result = pwRegex.test(sampleWord);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/regular-expressions/positive-and-negative-lookahead

You’re missing an element from the second half of the expression that checks for non-digit characters. Check out the MDN documentation for regular expressions regarding the missing element. :wink:

1 Like

Hmm I see. Thank you for your reply! But I don’t understand why is there a need to check for non-digit characters in the second half, is it possible for you to explain to me? Sorry if I’m troubling you! Appreciate the help :smile:

No problem. The second part of the regex doesn’t just check for the presence of numbers. If the string is only made up of numbers it’s not a valid password. It has to be at least 5 characters in length (part one of the regex), and it needs two consecutive digits.

1 Like

Thank you so much :blush: Your explanation helped a lot!

1 Like

Hey man, I just double checked the reason as to why \D* is required in the second regex and I think I understand better now. It’s actually because we are looking for 2 consecutive digits at any point within the string that we are searching.

Since the regex engine looks right of its current position to check for lookaheads, the \D* is necessary because we don’t want the regex to only be checking the start of the string for consecutive digits. By adding \D*, we are actually allowing the lookahead to check the entire string for any position which has 2 consecutive digits, and if so the result returns true. The password can be fully made up of numbers.

1 Like