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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With