REGEX: Restrict Possible Usernames - What's wrong here?

let username = "JackOfAllTrades";
let userCheck = /[A-Za-z][a-zA-Z]+[0-9]*$/ig; 
let result = userCheck.test(username);

Your regex should match JACK
Your regex should match RegexGuru

While I could code a solution for the lesson, I can’t figure out why this particular Regex is not acceptable to fill the requirements.

I already tried “/^[A-Za-z][a-zA-Z]+[0-9]*$/ig” in case those strings not matched were starting with a whitespace, but it seems they don’t, for it has not worked either.

Any thoughts?

1 Like

don’t use the g flag with a method before knowing what’s doing

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.


Hey there again, ieahleen! :slightly_smiling_face:

Thanks for your good-will to teach, your replies have been hitherto always very useful!

If I got it right, then a global run works by searching for a match, updating the value of lastIndex, storing the matched data, then searching again from the updated index onward, until the string ends (when lastIndex gets greater than the length of the string).

Nevertheless, I have still failed to figure out what determines lastIndex value.:man_facepalming:

var regex1 = new RegExp( "foo", "g" );
var str1 = 'table football, foosball';


// expected output: 9


// expected output: 19

Why is expected out put 9, then 19?

Oh, we’re looking for ‘foo’, and search is zero-index based.

So, after the first test, lastIndex will have a value of 9 and next search will start a “t” of football, which is the 9th character.

Well, duh :man_facepalming:

Thanks again anyways! :grin:

1 Like

lastIndex starts at 0, then after a string is tested, lastIndex is moved after the part of the string that tests true, foo is at indexes 6, 7 and 8. so next time it starts checking at index 9

Yeah, I figured out :stuck_out_tongue:

BTW, we really could have some extra explanation on backfunctions and how things work behind the scenes. When the lesson presented g flag, it was simply like “use it to keep searching after a match”.

Community support is vital to make FCC campers functional coders, I suppose :wink:

well, one could also check on the documentation each of the methods presented… :wink: