Restrict Possible Usernames: Unexpectedly Solution

Tell us what’s happening:
I was tinkering around trying to solve this, and unexpectedly solved it incorrectly. My /[A-Z]\w/gi passes not only the initial test, but if I change the username to “c” it passes. I thought it seemed a bit off because I hadn’t attempted to match the 2 digit requirement. When I looked at the solution, it seems I’m not close to passing it correctly.

Would someone be able to explain to me how it is that this seems to be tricking the system?


Your code so far

let username = "JackOfAllTrades";
let userCheck = /[A-Z]\w/gi; // Change this line
let result = userCheck.test(username);

Your browser information:

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

Link to the challenge:

Thank you for helping make FCC better. Bugs can be reported as GitHub Issues. Whenever reporting a bug, please check first that there isn’t already an issue for it and provide as much detail as possible.

1 Like

One issue you have is that using the g flag with the test method will result in unexpected things (if you don’t know what you are doing) and you shouldn’t totally be using it here

If the regex has the global flag set, test() will advance the lastIndex of the regex. A subsequent use of test() will start the search at the substring of str specified by lastIndex ( exec() will also advance the lastIndex property). It is worth noting that the lastIndex will not reset when testing a different string.

From here:

Uh oh, I’ve been using /g pretty much since the lesson on it… I wonder how many other answers I submitted that weren’t good. Thank you for the information, I’m definitely going to have to get a better handle on how that works.

You’ll find some challenges fail in the future if you use the global flag.

1 Like