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);


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/ 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!

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