Is there something wrong with my code? - JS module project

Tell us what’s happening:
Hello! I’m having some issues with the “Telephone Number Validator” project in the JS module. I have created a regex to match all the allowed phone number formats.

When I run the tests, the tests fail for the following number formats: “1 555-555-5555”, “1 (555) 555-5555”, “5555555555”, “555-555-5555”, “(555)555-5555”, “1(555)555-5555”, “1 555 555 5555”, “1 456 789 4444”. These should all return true according to this challenge.

As you can see in my code, I did a console.log() and the weird thing is that in the console, for all the aforementioned numbers the console displays “true”, but even so, the tests fail. I also tested my regex on and it shows it’s a full match with all these numbers.

Could you please help me out?

  **Your code so far**

function telephoneCheck(str) {
let regex = /^((1)?(\s|-)?(([(\[])?([0-9]{3,4})([)\]])?(\s+|-)?)+)$/g; 
return regex.test(str);

telephoneCheck("1 456 789 4444");

  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.101 Safari/537.36

Challenge: Telephone Number Validator

Link to the challenge:

There’s something super weird happening …

Explanation from the docs ( still find it confusing though, where is that information about the previous match stored?):

As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match.

The “flipping” will stop if you remove the console.log in your function, but you still won’t pass all tests, telephoneCheck("55555555") for example should return false while your function returns true.

1 Like

Thanks so much! It is indeed confusing but now the function at least returns true for the format numbers that are correct. I will polish the regex in order to pass all the tests.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.