Why doesn’t this code work?
The way I am reading it is that:
the first character must be a letter,
the + means the second character must also be a letter
the rest of the code means that the final character can be a number (or not)
What am I reading wrong?
Your code so far
let username = "JackOfAllTrades";
let userCheck = /^[a-z]+\d*$/ig; // 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/74.0.3729.169 Safari/537.36.
Link to the challenge:
Well, the first thing is that
[a-z] only catches lowercase letters. If you want uppercase letters too, it’s
[a-zA-Z]. Go to regexr.com and paste in your regular expression. At the bottom in the tools section (make sure it’s on the explain part), it will explain your regex. Also, you can find a regex reference and cheatsheet, search for existing regexes under community patterns, and more.
Except that his regex is using the
/i flag, so it’s case-insensitive.
/g flag is a problem though – try removing it so the regex is just
/^[a-z]+\d*$/i. That will leave you with just one test failing, but you should be able to figure that one out.
Oh , sorry. I noticed that case-insensitive thing, but my brain thought it meant case-sensitive for some reason.
+ means “one or more” and the
* “zero or more”.
Almost there - with this code (without the
g flag) it would be accepted also an username like “A”, but it is against challenge requirements
This is why you shouldn’t be using the
Using test() on a regex with the global flagSection
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
exec() will also advance the
lastIndex property). It is worth noting that the
lastIndex will not reset when testing a different string.