Friday, 28 April 2017

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)?



via Jordash

No comments:

Post a Comment