Working through the freeCodeCamp JavaScript curriculum and I found this RegExp task surprisingly tricky (maybe I just don't use RegExp very much).
The parameters are:
- Usernames can only use alpha-numeric characters.
- The only numbers in the username have to be at the end. There can be zero or more of them at the end. Username cannot start with the number.
- Username letters can be lowercase and uppercase.
- Usernames have to be at least two characters long. A two-character username can only use alphabet letters as characters.
My logic is that since usernames must start with a letter we can begin with /^[a-zA-Z]/i
.
From there, a username can contain either:
1 or more letters, followed by 0 or more numbers at the end of the string
OR
2 or more numbers at the end of the string.
Which lead me to the following RegExp: /^[a-z]([a-z]+\d*$|\d{2,}$)/i
. This RegExp works but I don't write that much RegExp so I'm not confident it's as simple or elegant as it could be.
[a-z]
), or Unicode letters? For usernames you may want the latter. \$\endgroup\$(?:\d+)?$
(a non-capturing group matching zero or one time) \$\endgroup\$