MonkeyBonkey
MonkeyBonkey

Reputation: 47901

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

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.

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})$/

Upvotes: 4

Views: 1326

Answers (1)

Federico Piazza
Federico Piazza

Reputation: 31045

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

Upvotes: 2

Related Questions