How is d different from \ d?

How is d different from \ d?
0.0 0

#1

In Regular Expressions: Restrict Possible Usernames,

let username = “JackOfAllTrades”;
let userCheck = /[a-z]|\d$/ig; // Change this line
let result = userCheck.test(username);

is incorrect, but,

let username = “JackOfAllTrades”;
let userCheck = /[a-z]|d$/ig; // Change this line
let result = userCheck.test(username);

is correct.

The only difference is d and \ d. How are these two different? (The second line of this code.)


#2

\d$ means “It has to end with a number”
d$ means “it has to end with the character d”

Here some reference : MDN - RegExp


#3

Hey!

I totally missed that, shouldn’t \d$ be used given that the task asks that:


#4
  1. The only numbers in the username have to be at the end. There can be zero or more of them at the end.

  2. Username letters can be lowercase and uppercase.

  3. Usernames have to be at least two characters long. A two-letter username can only use alphabet letter characters.


#5

I replied to the specific question ( the difference from d$ and \d$ ): about the challenge, if the ones in the last post are the only conditions, I’d suggest to use \d*$ - the* means 0 or more.

To avoid misunderstanding this is the meanings of the first two regExp posted:

let userCheck = /[a-z]|\d$/ig;

  • Will match every string with a letter ([a-z] means it search for any character from a to z, the i flag means case unsensitive) OR (|) ends with a number

It doesn’t pass the challenge because it will match 007 (which should not).

NOTE:
I just tested it and it will satisfy the last condition: it should not match 9, but if you replace “JackOfAllTrades” with 9 or “9” and log the result is true as it should be - so this is a bug (probably related to the ‘g’ flag).

let userCheck = /[a-z]|d$/ig;

  • Will match any string with any letter OR any string which ends with the letter d ( obviously redundant)

In short it will match any string that contains at least a letter, enough to pass the provided test cases ( even if it does not match the instructions )


#6

Thanks!

That’s a fantastic explanation!


#7

I am currently on this challenge, and initially was pretty stuck on it, I decided to do a quick search on the forums to see if others were stuck, hopefully get a hint on where I was going wrong… anyhow, I found this thread: Regular Expressions - Restrict Possible Usernames

@Saymon85 mentioned looking into quantifiers… and @chinonsoebere mentions looking at regex101.com as a place to test your expressions. After following their advice, I believe I have come up with a solution which should pass the tests, however, it doesn’t!

My solution is this:

let userCheck = /^[a-z]{2}|^[a-z]{2,}\d$/gi; // Change this line

Is anyone able to verify it is correct?

Thanks