Telephone number verification help

Telephone number validator challenge link

Hi I am not able to pass 3 cases. How do I put a condition so that 3 digits must be surrounded by 2 parenthesis at the same time. For example I want to return true if “(555)” but false for"(555" and false for “555)”. So the area of code to look at is ^1?\s?\W?\d{3}\W?.. What do I do to put condition so that \W around \d{3} must be present at the same time. If this is not the way of looking at this problem please guide. Thank you

function telephoneCheck(str) {
  let regex = /^1?\s?\W?\d{3}\W?\W?\d{3}\W?\d{4}$/gi;
  return regex.test(str);
}

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

Hello!

Well, the parentheses are special characters on a regular expression, hence you need to escape them to be able to use them as part of the string to match.

To escape the parentheses, prepend a \:

const regex =/\([a-z]\)/
console.log(regex.test('(a)')) // true
console.log(regex.test('(a')) // false
console.log(regex.test('a)')) // false
console.log(regex.test('a')) // false
1 Like

Thank you
Another question related to this.
if I do

let regex = /^1?\s?\W?\d{3}\W?\W?\d{3}\W?\d{4}$/gi;

than it will not make these false
(555-555-5555, 555)-555-5555, 1 555)555-5555
So if I use

let regex = /^1?\s?\(\d{3}\)\W?\d{3}\W?\d{4}$/gi;

now it won’t return true
1 555-555-5555
so I was thinking of doing

\(? and \)? 
//or
[\(\s-] and [\)\s-]

but in the above case if I have parenthesis just on 1 side it will return true which is not what I want.
Please help

Hmm, it’s hard helping here without giving your the answer :stuck_out_tongue:.

However, you could try to solve the problem one step at a time:

  1. Match the most basic format: 15555555555
  2. Add matching spaces: 1 555 555 5555
  3. Search for hyphens: 1-555-555-5555
  4. Try to add the parentheses to the regex.

Check the tests section to see all the valid formats (and what’s considered invalid).

1 Like

Thank you for your time and guidance. I will try that.

do not use the g tag when you use the test method

1 Like