Checking usernames with regex

Tell us what’s happening:
Describe your issue in detail here.
can someone help me spot my mistake here?

Your code so far


let username = "JackOfAllTrades";
let userCheck = /(\w+\d{2}$)|(\w{2}\d*$)/gi; // Change this line
let result = userCheck.test(username);

Your browser information:

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

Challenge: Restrict Possible Usernames

Link to the challenge:

Look at the first error in the console:

"Your regex should not match the string 007"

So that is telling you that it is violating this rule:

“Username cannot start with the number.”

Notice that both of your subpatterns start with \w. So what does that tell you?

1 Like
/(\^[a-z]+\d{2,}$)|(\^[a-z]{2,}\d*$)/gi

just changed the previous code to this but it still gives the same error.

This is escaping the ^ so it is literally looking for the ^ in the username, so lose the \.

I think you just need to go through the rules again and make sure you take them all into account. I will give you a hint by saying that you are on the right track having two subpatterns separated with the OR pipe.

1 Like

does ^[a-z]{2,} mean that there should be at least 2 letters at the beginning? so it doesn’t match A%B3 because the second one is not a letter even though it should match?
This is how it looks now:

/^[a-z]\d{2,}$|^[a-z][a-z]+\d*$/gi

I just removed the g from this one and it worked. Could you please explain why g made the code fail?

Correct. You could replace ^[a-z][a-z]+ with ^[a-z]{2,}.

This is caused by a “quirk” with how the tests interact with the global flag. If you want to know all the gruesome details you can find them in this thread.

You don’t need the global flag here because you aren’t searching for multiple matches in a string. Each string being tested contains only one username and you are doing the pattern matching on the entire string, not trying to find sub-patterns in the username.

Yes, technically this challenge should pass with the global flag but adding the global flag is not needed in this case, so I would argue that the challenge is teaching you not to add things that aren’t needed :slight_smile:

1 Like