malcoauri February 2016

Format string as phone number in JavaScript/Lodash

There is the following phone number string: '+79021234567'. How can I format this string as '+7 902 123-45-67'? I can do it manually with substring, but may be there is more elegant way? Thanks in advance!

Answers


A.J. February 2016

str.substring(start, end) does seem to be the most applicable way, although it does not seem very elegant:

> str = '+79021234567'
> console.log([[str.substring(0, 2), str.substring(2, 5), str.substring(5, 8)].join(" "), str.substring(8, 10), str.substring(10)].join("-"));
+7 902 123-45-67

Post Status

Asked in February 2016
Viewed 2,047 times
Voted 14
Answered 1 times

Search




Leave an answer