JavaScript Algorithms and Data Structures Projects - Telephone Number Validator

Tell us what’s happening:
So I’m struggling with dealing with the single parentheses not closing off I thought capture groups would help but they didn’t seem to. I was thinking of lookaheads as well but that only looks at whats directly ahead of the item right? Same with country code. If I put 2 there is just doesn’t show up in the match, and i thought that would make the result false but it doesn’t. Any advice is appreciated, I really am unsure of how to proceed with this.

Your code so far

function telephoneCheck(str) {
  let regex = /(\(*1{0,1}\)*)\s*(\(*\d{3}\)*)-*\s*(\(*\d{3}\)*)-*\s*(\(*\d{4}\)*)/g;
  let bool = false
  if (str.match(regex)){
    return true;
  } else {
    return false;


telephoneCheck("2 (757) 622-7382");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/114.0

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

Link to the challenge:

What a conincdence, i was investigating the look head recently.
The lookahead explanation from rexegg helps me alot >> Lookahead and Lookbehind Tutorial—Tips &Tricks

Maybe you wan to make use of following combination?

| () ?  ^ $ {}` ( | ) []?

I tried to use lookahead with a OR condition, then found it is solvable with lookahead too, but my solution is quite long to match every case:

If you want stricter condition, maybe you want to rebuild your regex with begining/end control.

let regex = /^   $/

Try to dig further into pattern of the VALID format, and what are the difference from the INVALID format. It would give some clues.

// Valid format
(555) 555-5555
555 555 5555
1 555 555 5555
Invalid format
1 555)555-5555
2 (757) 622-7382
11 555-555-5555

I appreciate your suggestions and wasn’t having too much success with the lookaheads or lookbehinds unfortunately but the beginning and end control helped, I also realized some of the stuff could have been more specific but now I’m passing all the tests but three. This is my new Regex let regex = /^(?(1{0,1}))?[- ]((\d{3}))[- ](\d{3})[- ]*(\d{4})$/g;. i’m still struggling with if there is only a singular parentheses and am still unsure of how exactly I need to include it.

I figured I should let you know I figured it out. Tanks again for the advice.

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