US telephone... Almost passed but... [SPOILER]

Hi! I know that this is not the cleaner and much elegant code to solve this challenge, but I can’t figure out why my code does not pass the (555)555-555 test case. This string meets all the if statements requrements but returns false. Any hints?
Here is my code.

#spoiler!

function telephoneCheck(str) {
 
  var num = parseInt(str);
  if(num.toString().length == str.length && str.length > 10 || str[0] == "(" && str.length > 12) {
    return false;
  }  
  
  if(/[(]\d{3}(\))/g.test(str) === true || /[)]/g.test(str) === false) {
    if(/^[1](?![\d])/g.test(str) === true || /^[(]{0,1}\d{3}[)]{0,1}/g.test(str) === true){  
      if(str.match(/[(]{0,1}\d{3}[)-]{0,1}[\s]{0,1}\d{3}[-\s]{0,1}\d{4}/g)) {
        return true;
      }
    }
  }

  return false;
               
}

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

It triggers this if statement: str[0] == "(" && str.length > 12, because it starts with ( and str has a lenght of 13.

1 Like

Thank you so much, @BenGitter! I was about to throw the laptop out the window. For now, I’ve decided to ‘resolve’ it adding another nested if statement inside that one (if(str[4] == ")" && str[8] == "-") {return true;}), but in the future I will come back to search a neater solution. (I must find out some resource that could help to deeper understand regexs and how to build them). Thanks again for your help.

1 Like