Another regex that works in regExr but not here?

…this is why I avoid regex like the plague…

I’m working on the phone number validator and I plug the regex in this code:

function telephoneCheck(str) {
let teleReg = /^[1]?[ -]?((\d{3}))|(\d{3})[- ]?\d{3}[ -]?\d{4}$/;

return teleReg.test(str);


into regExr (Javascript engine, no flags) and it works (i.e. the numbers I copied from my failing tests return true when they should and false otherwise) but not here in FCC.

these are failing:

telephoneCheck(“2 757 622-7382”) should return false.
telephoneCheck(“27576227382”) should return false.
telephoneCheck("(275)76227382") should return false.
telephoneCheck("(555-555-5555") should return false.
telephoneCheck("(555)5(55?)-5555") should return false.

Any tips/hints would be appreciated.



I just tried your expression on regexr and it gives the same results as FCC tests. For example, all your samples returned a positive match. Did you test the phone numbers with quotes around it? Like

"2 757 622-7382"

This will give you erroneous results.

Thank you. That explains it. …I’m removing the quotes. I’ll pay with it more tomorrow.

Putting the quotes back on regexr I get the same result. Hmmm…

You may please share the challenge link?! Thanks.

Oooohhhh…I see what’s wrong. RegExer is using “match” vs. “test” Now that I’m awake I plugged this all in to codepen and see that they react very different. “match” does not find a match. “test” returns true for 2 757 622-7382 with /^[1]?[ -]?((\d{3}))|(\d{3})[- ]?\d{3}[ -]?\d{4}$/. Now to go find why…

@NULL_dev: the challenge link is here:

1 Like

Your regex is wrong, and fails the tests.

best practice is have a list of possible accepted values in hand, such as following

1 555-555-5555
1 555 555 5555

Above are all possible formats.

now lets begin, it’s easy.
Your start of the pattern is true. looking for 1 with or without any space after it.
So: ^[1]?[\s-]?
Next if you check the samples too, it could be {(AAA)} or {AAA with or without a - or a space}
So mind the OR, and we have: ((\(\d{3}\)\s?)|(\d{3})[\s-]?)
And the rest is easy, 3 digits, either a space or - or nothing, and then 4 digits.
So just like what you applied: \d{3}[\s-]?\d{4}$

This ((\d{3}))|(\d{3})[- ]? is wrong, check the valid values above, and check the chained characters.

Fixi s very easy, you can do it, don’t cheat and reveal the spoiler, do it.

Keep going on great work, happy programming.

Got it! Thank you NULL_dev. Got it working with a bit of playing around…in spite of babysitting a production change for the day job at 3:30am :wink:

And I think I know why regExr gave me different results too…I suspect they are doing something a bit off…like regEx.match(str) which throws an error (because match is not a valid function for regex but is for string–i.e. they should do str.match(regEx) instead).

On that note…back to the coffee and my production change