JavaScript Algorithms and Data Structures Projects - Telephone Number Validator

Hello, I almost completed this project. However, there are still three error that I get. What could be missing?

Your code so far

function telephoneCheck(str) {
  //use regular expression
  let phoneNumRegex = /^\d{3}(\s|-)?\d{3}(\s|-)?\d{4}$|^1(\s|-)?\d{3}(\s|-)?\d{3}(\s|-)?\d{4}$/g
  
  return phoneNumRegex.test(str);
}

telephoneCheck("555-555-5555");

console.log(telephoneCheck("1 (555) 555-5555"));
console.log(telephoneCheck("(555)555-5555"));
console.log(telephoneCheck("1(555)555-5555"));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36

Challenge: JavaScript Algorithms and Data Structures Projects - Telephone Number Validator

Link to the challenge:

Hi @selimyay, I saw that the second two errors were involving a 1 followed by the brackets, which wasn’t included in your solution.

All that looked like it was missing was identifying if a 1 is there or not. So rewriting it, with this included, it would look something like this:

let phoneNumRegex = /^1?[-\s]?(\d{3}|\(\d{3}\))[-\s]?\d{3}[-\s]?\d{4}$/

Which really isn’t that different to your solution, it just moves it to the front, with the following:

The 1? matches an optional β€œ1” character. The question mark makes the preceding β€œ1” character optional. The [-\s]? matches an optional hyphen β€œ-” or whitespace character β€œ\s”. The square brackets define a character set that matches either β€œ-” or β€œ\s”, and the question mark makes it optional.

1 Like

thank you so much for the answer, it worked. However, as I see, you added some extra \ and ( ) to the code. I guess ( ) is for (555) etc. but I don’t understand why you use extra \ ? for example here: \ (\d{3}|(\d{3}))

Hi, no problem! So the backslash is used to escape the brackets. So that the brackets aren’t evaluated as part of the regular expression, but instead are their actual characters.

1 Like

I learned something new, thanks again!