0

#1

Hello!

I always try to test the example code in the various way.
But seems like example has error.
Could you check and help me to figure out my questions?

1. “password” has to be 3~6 characters .
I put “password” as “abcdefg1” which is 8 letters but this code returns “true”. (Please check below capture and the link of CodePen)
Length of “password” is over than 6 letters that it has to return “false”.
Why is it “true”?

2. “checkPass” includes two brackets : /(?=\w{3,6})(?=\D*\d)/
. First bracket means : 3~6 characters of A-Za-z0-9_ is required
. Second bracket means : zero or more non-number is required -> \D* + number is required -> \d
Can order be changed? like (?=\d\D*)
. (…)(…) can be equally functioned at the same time.
=> Am I understanding correctly?
Then can I use /(?=^a)(?=\w{3,6})(?=\D* \$\d)/ as “password has to be start with a and 3~6 letters and at least one number is required, ending with only number”?

[Example]
Here is a (naively) simple password checker that looks for between 3 and 6 characters and at least one number:
let checkPass = /(?=\w{3,6})(?=\D*\d)/;

#2

I’ll try to answer this. If I’m wrong, anyone can correct my answer.

The positive and negative lookahead does not match anything. They’re just there to help find something you want to match. In your code, `/(?=\w{3,6})(?=\D*\d)/` is asking for “something” followed by a group of 3 to 6 letters, numbers and/or underscores and also followed by a group of any number of non-digits ending with only one digit. “abcdefg1” meets the criteria because you have 6 characters (a to f), then one non-digit (g) followed by a digit (1).

In your screenshot, `d` is returning `true` because the lookahead was found as your password matches the regex (two lookaheads found), but `c` is returning an empty string because you didn’t explicitly ask for anything before the lookahead. For example, if you want to return any digit before the lookaheads, you would write the regex like this: `/\d(?=\w{3,6})(?=\D*\d)/`; and if you now set your `password` equals to `1abcdefg1`, then `["1"]` will be stored in the variable `c`.

The order in the lookaheads is important because you want to find an exact order of appearance in the string. /(?=\D*\d)(?=\w{3,6})/ won’t match the same structure in the string as you’re looking for something followed by some non-digits, then a digit, then 3 to 6 letters, numbers and/or underscores.

Hope it helps understanding the matter a little better.

PS: I personally don’t think the challenge in FCC is a clear example on how to use pos/neg lookaheads, but that’s what we have