Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

Where do I place the method for the seventh character so 020 7686 1111 is returned?

Any help is appreciated. Thanks in advance!

like image 828
realph Avatar asked Nov 30 '22 18:11

realph


2 Answers

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.

like image 105
Karl-André Gagnon Avatar answered Dec 10 '22 11:12

Karl-André Gagnon


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.

like image 28
Matt Burland Avatar answered Dec 10 '22 13:12

Matt Burland