Hey everyone
I’m working on the “Build a Telephone Number Validator” project in the JavaScript course, and I’m trying to build a regex to match all valid formattings of a U.S. phone number. As far as I understand, a US phone number is very precisely formatted as such (I omitted the plus sign “+” in the country code because fCC did):
- Optional country code “1”
- Optional space " "
- Optional opening parenthesis “(”
- 3 digits
- Optional closing parenthesis “)” (if opening parenthesis was used)
- Optional space " " or dash “-”, but not both
- 3 digits
- Optional space " " or dash “-”, but not both
- 4 digits
The examples of valid formatting provided by fCC for the project are:
1 555-555-5555
1 (555) 555-5555
1(555)555-5555
1 555 555 5555
5555555555
555-555-5555
(555)555-5555
To match this, I wrote the following regex and was testing it as follows:
const phoneRegex = /1? ?\(?\d{3}\)?( |-)?\d{3}( |-)?\d{4}/;
console.log(phoneRegex.test(/* Inputs here */));
Unfortunately, I’m not very good at regexes , and so some of the test strings that should return false
returned true
. For example,
const phoneRegex = /1? ?\(?\d{3}\)?( |-)?\d{3}( |-)?\d{4}/;
console.log(phoneRegex.test("qqqqdasdfsdf;34555555244444422255555"));
returns true
, when it obviously shouldn’t. Please explain to me what I’m doing wrong.
Thank you very much!
Side question: How do I make the regex match if the first group of the three digits has parentheses around it, but only if both are there? That is, how to match
"1(234)5678912"
but not
"1(2345678912"
or
"1234)5678912"
Thank you very much!