What is the problem of this code

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**

function telephoneCheck(str) {
// if str starts with a dash, return false, else replace dashes and spaces with nothing
if (str[0] == "-"){
  return false;
}else
  
str = str.replace(/-|\s/g, "");
//Location of first parentheses 
var firstPar = str.search("\\(");
//Location of second parentheses
var secondPar = str.search("\\)");
//Length of the str
var strLen = str.length;

//Depending on string length
switch(strLen){
    
  case 10:
    return true;
    
  case 11:
    if (str[0] == 1){
      return true;
    }else
      return false;
    break;
    
  case 12:
    if (str[0] === "(" && str[4] == ")"){
      return true;
    }else
      return false;
    break;
    
  case 13:
    if (str[0] == 1 && firstPar === 1 && secondPar === 5){
      return true;
    }else
      return false;
    break;
  default:
    return false;
}
}



telephoneCheck("555-555-5555");
  **Your browser information:**

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36

Challenge: Telephone Number Validator

Link to the challenge:

Log out strLen with this call.

telephoneCheck("55 55-55-555-5")

Which case will it match?

Please write the all code

I don’t know what you mean, just console.log strLen after you set it.

var strLen = str.length;
console.log(strLen);

And call the function with the argument from the last test.

telephoneCheck("55 55-55-555-5");

Look at the length and see which case it will match in your switch. It should be obvious why the last test fails.

I find the answer finally :slight_smile: :slightly_smiling_face:

function telephoneCheck(str) {
  var regex = /^(1\s?)?(\(\d{3}\)|\d{3})[\s\-]?\d{3}[\s\-]?\d{4}$/;
  return regex.test(str);
}

telephoneCheck("55 55-55-555-5")

Did you write the regex or just search for it?

There isn’t anything wrong with using a premade regex (IRL) but in this case, it would have been better to get your own solution working first. Not that I would suggest it over using a regex.

Anyway, hopefully, you understood what the problem was with your initial code.


Edit: I blurred the code just to avoid spoilers and formatted it.

When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).