Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modify a phone number cleanup regex to handle a leading 1 digit

Tags:

regex

I have a regex that already takes care of standardizing formatting of U.S. phone numbers, however it doesn't deal with a leading 1.

var cleanTelephoneNumber = function(tel) {
  var regexObj = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
  if (regexObj.test(tel)) {
    return tel.replace(regexObj, "($1) $2-$3");
  } else {
    return null;
  }
};

how can I get it to strip out a leading one if it exists and still continue to parse correctly

e.g.

  • +1-555-235-2444
  • 1-555-235-2444
  • 1.555.235-2444
  • 1 555 235 2444
  • 555-235-2444

should all translate to (555) 235-2444

I'd like to just modify the regex I already have

/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/

like image 782
MonkeyBonkey Avatar asked Jan 01 '26 02:01

MonkeyBonkey


1 Answers

You can modify your regex to use this:

^(?:\+?1?[-.\s]?)(\d{3})([-.\s])(\d{3})\2(\d{4})$

Working demo

enter image description here

The idea of the regex is:

^(?:\+?1?[-.\s]?) can have +1 and a separator
 (\d{3})          must contain 3 digits
 ([-.\s])         store a separator
 (\d{3})          follow by 3 digits
 \2               use the same separator
 (\d{4})$         follow by 4 digits
like image 71
Federico Piazza Avatar answered Jan 05 '26 11:01

Federico Piazza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!