简体   繁体   中英

Javascript, normalize Phone Number Strings with regular Expression

I'm really new to regular expressions but here is what I am trying to do.

I have a phone number input and I need it to be converted into a string like this:

'2228883333'

The user could potentially type it in like any of the following:

222 888 3333
(222) 888 3333
12228883333
1 222 888 3333
1 (222) 888 3333
2228883333
+1 222 888 3333

I want to allow the user to type it in however they are most used to and then convert the phone number to my desired format on the server side (NodeJS)

Here is the regular expression I tried from PHP but I can't figure out how to do it in Javascript.

var number = req.body.phone;
    number = number.replace('~.*(\d{3})[^\d]{0,7}(\d{3})[^\d]{0,7}(\d{4}).*~', '$1$2$3');

Any idea how to accomplish this in NodeJS (Javascript)?

If you do exactly what you described, your system will fail the first time someone tries to enter a phone number from outside of the US.

I would suggest keeping the +1 (or just 1) in the number and adding it only if the number doesn't include other country code already.

What I would do here:

  1. remove anything except digits and a plus (and possibly convert leading 00 to +)
  2. if the string starts with a plus, don't add anything
  3. if the string starts with 1, add a plus
  4. if the string starts with anything else than a plus or 1, add +1

Example:

var number = req.body.phone;
number = number.replace(/[^\d+]+/g, '');
number = number.replace(/^00/, '+');
if (number.match(/^1/)) number = '+' + number;
if (!number.match(/^\+/)) number = '+1' + number;

Now, for all of the numbers:

222 888 3333
(222) 888 3333
12228883333
1 222 888 3333
1 (222) 888 3333
2228883333
+1 222 888 3333

plus some extra:

001 222 888 3333
001 (222) 888 3333
001(222)888-3333

you should have one normalized representation, but this time it is:

+12228883333

which supports international numbers. You might remove the plus if you want:

number = number.replace(/^\+/, '');

but I would recommend to keep it so that it is clear that this number includes the country code for anyone who processes that data and this is a number that anyone can dial directly all over the world.

This is easy enough to do with two regex replaces:

const unformatPhone = phone => phone.replace(/\D/g, '').replace(/^1/, '');

This is probably much cleaner than anything you might find with a single regex.

The first regex, /\\D/g matches any non-digit characters. The second, /^1/ matches a leading '1'. Both are removed by replacing them with an empty string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM