So I reached the “Restrict Possible Usernames” lesson in the “Regular Expressions” course
I wrote the right RegEx to pass the test (/^[a-z][a-z]+\d*$|^[a-z]+\d\d+$/gi) and even tested it on an another RegEx checker website with the test examples from the lesson
I put my code in the right place, but after I press the “Run the Tests” button to pass the test, I can’t pass it, and the console output writes me that my RegEx doesn’t match strings it should match
But as soon as I add the username.match(userCheck); line to the test - I’m able to pass it
I just re-tried doing this lesson. Our regex is almost the same, but what I did notice was your use of the //g flag. I only passed along the //i flag, and that seemed to work on my first try.
Bottom line, don’t use the global flag when using RegExp.test unless you understand the repercussions. I don’t think I can recall ever using the global flag with this method. RegExp.test returns a boolean, so it is just checking if the pattern matches, it isn’t returning any information about the matches, so having the global flag doesn’t really make sense. The global flag would be used when you anticipate more than one match in a string and want the information for each of those matches (see discussion of return value for String.match).
It seems more of an issue that people don’t understand what the global flag does and are just adding it in there when it isn’t needed. If the variable username only contains one username then there is no reason to use the global flag regardless of the method used to test the regex.
Obviously, it’s a lack of knowledge about the global flag in the context of .test(). However, this has been a recurring issue and I know we did some fixes for other challenges.
I think it’s just because Match is a string method and lastIndex is a property on a RegExp instance.
The issue with this challenge isn’t really with the global flag. The problem is with the seed code advancing lastIndex. If you comment out (or remove) all the code except for the regex, it will pass the tests.
// let username = "JackOfAllTrades";
let userCheck = /^[a-z][a-z]+\d*$|^[a-z]+\d\d+$/gi; // Change this line
// let result = userCheck.test(username);