Regular Expressions: Restrict Possible Usernames // I am doing something wrong

Tell us what’s happening:
Dear fellow coders, I do not understand why is the following regex turning false.

I am failing the following strings

"JACK"
"Jo"
"Oceans11"
"RegexGuru"
"Z97"

Your code so far


let username = "JackOfAllTrades";
let userCheck = /^[a-z]{1,}\d*$/gi; // Change this line
let result = userCheck.test(username);

Funny thing is that they are all coming back like true when I test them in my browser with console.log
Do you maybe have some idea what I’m doing wrong?

Your browser information:

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

Challenge: Restrict Possible Usernames

Link to the challenge:

Whoops, sorry, disregard my previous post, I missed that you had the ‘i’ flag in there.

/^[a-zA-Z]{1,}\d*$/gi

I’v tried the above but still not passing the same strings as before. I think that with the i flag the search should be case insensitive: no difference between A and a

No problem, thank you for your help

Why are you using the global flag?


1 Like

OK, some better help now :slight_smile:

  1. Get rid of the ‘g’ modifier. You aren’t looking for sub patterns, you are looking for one pattern for the entire string. After doing that run the tests and see what you have left.
  2. You will see that you are now matching too many. What condition are they violating?
  3. Now rework your regex. Start with what every username will have in common. Then, with what remains, I think you will see that there are two possible patterns (either this pattern OR that pattern).
1 Like

Mind-bending :sweat_smile:
I am fixated on a particular pattern and cannot think the other way. I’ll try again in the morning with a clear head.

The tip to move the g flag was sweet and to be honest I do not know why I have used it but I still have problems with one string
Your regex should match Z97
I cannot pass the above string
My code so far is /^[a-z]{2}\^d|^[a-z]{2,}\d*$/i

You are very close. You are using the OR operator now which is exactly what you needed. You just need to rearrange your logic a little. What is the one thing that every username has in common? (Hint: It’s at the beginning of the username.) Start with that, and then use parens and the OR operator to catch all the possible matches.

2 Likes

Thank you very much!!
The solution that I have is quite long but at least it works :upside_down_face: