skip to Main Content

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


  1. Change your regex to [0-9]{3}-[0-9]{3}-[0-9]{4}

    You are using the {2,} means between 2 and infinite. So 2002-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.

    Login or Signup to reply.
  2. In your case you can try /[0-9]{3}-[0-9]{3}-[0-9]{2,}/.

    PS: this is not a javascript you use here, but regex. Here is useful site to try regexes out – https://regexr.com/

    Login or Signup to reply.
  3. It requires a pattern matching of 3 numerical values followed by - followed by 3 numerical values followed by - followed by 4 numerical values.

    const paragraph = 'call us at 517-156-4435 on the date 2002-01-23';
      const regex = /d{3}-d{3}-d{4}/g
      const found = paragraph.match(regex)[0];
      
      console.log(found);
      d{3} Matches exactly three digits.
      - Matches a hyphen.
      d{3} Matches exactly three digits.
      - Matches another hyphen.
      d{4} Matches exactly four digits.
     
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search