Js Regex not working as expected and as described in lesson

Tell us what’s happening:
in Regular Expressions: Positive and Negative Lookahead lesson about the below-given regex it is said that: " Here is a (naively) simple password checker that looks for between 3 and 6 characters and at least one number:" but unexpectedly it is returning true for alphabets more than 6 characters length
can someone please explain this behavior?

Your code so far
let password = “abc12399hjahgsah977”;
let checkPass = /(?=\w{3,6})(?=\D*\d)/;
let res =checkPass.test(password);
console.log(res);

Your browser information:

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

Challenge: Positive and Negative Lookahead

Link to the challenge:

> (?=\w{3,6}) = this is greedy lookahead for 3-6 chars of letters, numbers and underscore
> (?=\D*\d) = this is greedy lookahead for zero or more non digits, followed by a digit
> abc12399hjahgsah977 will match (?=\w{3,6}) since it contains or abc123 or hjahgs or sah977 etc, any 3-6 letters, numbers or underscore
> abc12399hjahgsah977 will also match (?=\D*\d) since it contains hjahgsah9 or abc1
The problem here is that the regex only checks what the password contains and does not check the entire password length equals 3-6.
You will need to include start_of_line ^ and end_of_line $ to restrict the total length of chars (?=^\w{3,6}$)
Remember you can use Regex101 for testing.

1 Like