Restrict Possible Usernames Clarification

Restrict Possible Usernames Clarification
0.0 0

#1

Tell us what’s happening:
Is this the order the Regex is going through when testing?

  1. ^[a-z] : the pattern must start with a letter
  2. [a-z]+ : the letter must be followed by one or more letter
  3. \d*$ : if there is 0 or more numbers they must be after the letters
  4. i : case insensitive

My issues :

  1. if I delete \d*$ and my string is “as12”, it returns true. Why return true if there is no regex for numbers?

  2. if the character $ means “match at the end of the string” why would it matter if I placed \d*$ at the start of the regex. Conversely if ^ outside of [] means match at the beginning why would it matter where ^[a-z] is placed?
    Your code so far


let username = "JackOfAllTrades";
let userCheck = /^[a-z][a-z]+\d*$/i; // 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/67.0.3396.87 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/regular-expressions/restrict-possible-usernames/


#2

Hi @s.sparkz

Because the string will partially match, which would be considered a pass for the test method. Have a look here to see the difference between using \d*$ and not.

Because regex isn’t like a list of instructions that can appear in any order, the tokens and matchers have to be in the order you expect them to appear in the string. So ^ would be at the beginning and $ would be at the end.


#3

Hello joesmith100,

So “as12” returns true as a partial match to /^[a-z][a-z]+/i.

“12” returns false to /^[a-z][a-z]+\d*$/i.

Isn’t “12” as much a partial match to /^[a-z][a-z]+\d*$/i as “as12” is to /^[a-z][a-z]+/i?


#4

No, because the regex is expecting at least 2+ characters (a-z) to proceed the digits in the string. Since that string contains no characters it can’t match.

Remember, regex isn’t a list of instructions, it’s a pattern and if the string doesn’t match the pattern properly it won’t match.

as12 is a partial match against ^[a-z][a-z]+ because it expects those characters at the beginning of the string.