I don't understand how the following code is being returned as true

Tell us what’s happening:
I cleared this challenge and i was trying different stuff, and i got stuck with this .
Can someone explain to me how is this returning output as true

I don’t understand how the "rnam3" is being passed using this regex.
i purposely dint include the brackets required to complete this challenge.

Your code so far


let username = "BadUs3rnam3";
let userCheck = /^[a-z][a-z]+\d*|\d\d+\d*$/i; // Change this line
let result = userCheck.test(username);
console.log(result)

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.4 Safari/605.1.15.

Challenge: Restrict Possible Usernames

Link to the challenge:

Can you describe what you think this regex does?

1 Like
^[a-z]  // checks whether the string starts with a small letter character
[a-z]+ // followed by 1 or more small letter characters
\d*  // followed by  0 or more digits

I am sorry if i dint get it right …my basics are not really solid yet, and i am not confident with my given answer to your question.

Alright, sounds good!

So rnam3 passes your regex,
because it starts with a small letter, r,
followed by 1 or more small letters, nam,
followed by 0 or more digits, 3.

There is also a great tool to check your regex

Or did I misunderstand your original question?

1 Like

Because .test() search for a match. It matches “BadUs3” in your string, hence, it returns true.

As far as I understand, the regex will either match:
(a letter “at the start of string”)(one or “n” quantities of letters)(0 or “n” digits)

OR

(a digit)(“n” digits)(0 or “n” digits “at the end of string”)

Therefore it will return true for string such as:

BadUs3rna01020102011
BadUs3rNam3
BadUs3
rnam3
11
122345525
1 Like

Ah…but my question was different…this is what I understand from the regex

In the string BadUs3rnam3

B gets passed cause of ^[a-z]
adUs gets passed cause of [a-z]+
3 gets passed cause of \d*

Then the rest rnam3 how does this part get passed cause after \d* comes the OR operator .

This is a very basic problem that I don’t understand … sincerely hope you can explain

Yes …you are correct. Thank you
I was under the impression it matches the whole string

You’re welcome.
This is outside of this problem’s scope. But, If you want the .test() to match the whole thing:

/^[a-z][a-z]+\d*$/i

Include a “$” character at the end of string .

$ Matches the end of the string, or the end of a line if the multiline flag ( m ) is enabled. This matches a position, not a character.

Along with “^”, ^(any other regex)$ together, these tell the pattern to only match an exact String, rather than also a match within a string.

1 Like

ohh wow…thanks man…these basics i dint have any clue about them…You are a lifesaver man