Live Regex Phone Formatting

In AngularJS, I need to format phone numbers while typing them. I do not want to use any library, as it should be straightforward.

I need a format: 99 99 99 99 99

var phone = tel.replace(/\D*(\d{2})\D*(\d{2})\D*(\d{2})\D*(\d{2})\D*(\d{2})\D*/, '$1 $2 $3 $4 $5');

But it only formats my number as soon as it has been completely dialed. How can I make this regex work when the number is not yet complete?

Then I tried this:

var phone = tel.replace(/\D*(\d{2})\D*(\d{0,2})?\D*(\d{0,2})?\D*(\d{0,2})?\D*(\d{0,2})?\D*/, '$1 $2 $3 $4 $5');

But this is obviously the addition of non-required spaces.

+4
source share
2 answers

You say you want it to be “straightforward,” but you artificially limit the problem (forcing the solution to be just a regular expression) when a pure regular expression is actually a bad solution to this problem.

? (), , - .replace() .

JavaScript :

// Get only the digits from the string
var phoneDigits = tel.replace(/\D/g, "");
// Join together the first up-to-5 pairs of digits with spaces,
// allowing for a singleton if the number of digits is odd.
var phone = (phoneDigits.match(/\d\d?/g) || []).slice(0,5).join(" ");

( || [] , null, .)

+4

.

var phone = tel.replace(/\D*(?:(\d{2})\D*(?:(\d{2})\D*(?:(\d{2})\D*(?:(\d{2})\D*(?:(\d{2})\D*)?)?)?)?)?/, '$1 $2 $3 $4 $5');

 \D* 
 (?:
      ( \d{2} )                     # (1)
      \D* 

      (?:
           ( \d{2} )                     # (2)
           \D* 

           (?:
                ( \d{2} )                     # (3)
                \D* 

                (?:
                     ( \d{2} )                     # (4)
                     \D* 

                     (?:
                          ( \d{2} )                     # (5)
                          \D* 
                     )?
                )?
           )?
      )?
 )?
0

All Articles