Help with Validate US Telephone Numbers

Help with Validate US Telephone Numbers
0

#1

Hello, friends!

I’m currently doing some advanced algorithm and I’m stuck with my solution. FCC suggests regex to solve this exercise, but I tried to use regular if statements and almost everything works, but some cases keep returning wrong answers. I really don’t get what’s the difference and why the code is not working properly.


function telephoneCheck(str) {
  // Good luck!
  var arr = str.split("");
  var newArr = [];
  arr.forEach(function(number){
    if (isNaN(number) === false && number !== " "){
      newArr.push(number);
    }
  });
  if (newArr.length === 10){
    return true;
    
  } else if (newArr.length === 11) {
    if (newArr[0] == 1) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
 }



telephoneCheck("1 555-555-5555");

As always, thanks a lot for your attention and help :slight_smile:


#2

Your solution creates newArr by only pushing numbers and ignores symbols like ( and ), which in the challenge are important to look at in some of the test cases. For example, in the following case:

telephoneCheck("1 555)555-5555"); // should yield false

Your solution does not recognize the ) is missing a ( four characters before it.

Another example is in the following case:

telephoneCheck("-1 (757) 622-7382"); // should yield false

Your solution is ignoring the minus sign before the one, so it does not see a problem. Valid US phone numbers do not start with -1.


#3

Thanks a lot, @RandellDawson! Makes total sense. I feel like I need to study more about regex. If you have any extra content, I’ll really appreciate.