I have the following code to match phone numbers and store them in variable "phone". however it also matches dates as phone numbers. for example, if I give it the following string:
html.Code = 'call us at 517-156-4435 on the date 2002-01-23'
the following match function saves both '517-156-4435'
& '2002-01-23'
. how would I adjust the code so it only saves the '517-156-4435'
number?
phone = htmlCode.match(/[0-9]+-[0-9]+-[0-9]{2,}/)[0];
I had no idea what other steps to take to troubleshoot this issue, I’m just starting out learning javascript so anything helps.
3
Answers
Change your regex to
[0-9]{3}-[0-9]{3}-[0-9]{4}
You are using the
{2,}
means between 2 and infinite. So2002-01-23
has two digits (23) and therefore matches it.Assuming your phone number would always be in the format of
012-345-6789
, then[0-9]{3}-[0-9]{3}-[0-9]{4}
should work for you.In your case you can try
/[0-9]{3}-[0-9]{3}-[0-9]{2,}/
.PS: this is not a
javascript
you use here, butregex
. Here is useful site to try regexes out – https://regexr.com/It requires a pattern matching of
3 numerical values followed by - followed by 3 numerical values followed by - followed by 4 numerical values
.