Skip to content Skip to sidebar Skip to footer

Split And Add Space Between Phone Number

I'm trying to format a telephone number into a neater format that adds a space between every third and seventh character from the front. Where do I place the method for the sevent

Solution 1:

In a single replace :

var string = "02076861111"
var phone = string.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3');
console.log(phone);

Of course, that assume you always have a perfect string (no space, hyphen or other characters, 10 character...)

A more strict regexp could be like this :

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

But still, that wouldn't catch every possibilities.


Solution 2:

Just slice it again:

var phone = [string.slice(0, 3), " ", string.slice(3,7), " ", string.slice(7)].join('');

Slice takes a start and (exclusive) end index. Note, if the end index is missing, it'll take the rest of the string.

So the first slice takes index 0 thru 2, the second takes index 3 thru 6 and the last slice takes index 7 to the end of the string.


Solution 3:

Why use slice, when a regular expression can work

"02076861111".replace(/(\d{3})\D?(\d{4})\D?(\d{4})/,"$1 $2 $3");

and this will not blow up if the user enters in spaces to start.


Solution 4:

An alternative solution:

function numberWithSpaces(value, pattern) {
  var i = 0,
    phone = value.toString();
  return pattern.replace(/#/g, _ => phone[i++]);
}

console.log(numberWithSpaces('02076861111', '### #### ####'));

Solution 5:

"02076861111".replace(/^\d{3}-\d{8}$/);

OUTPUT: 020-76861111


Post a Comment for "Split And Add Space Between Phone Number"