I’m trying to format a phone number as a user types, and I’ve almost got it, but I just can’t seem to bring it home.
Here’s what I’m looking for:
+12345678900 --> +1 (234) 567 89-00
+1234567890 --> +1 (234) 567 89-0
+123456789 --> +1 (234) 567 89-
+12345 --> +1 (234) 5
+123 --> +1 (23
Here’s my approach:
'+12345678900'
.replace(
/^(+d{1})?(d{1,3})?(d{1,3})?(d{1,2})?(d{1,2})?$/,
"$1 ($2) $3 $4-$5"
); // +1 (234) 567 89-00 ✔️
It works with a full number, but fails for other cases, here are some of them:
+12345678 // expected '+1 (234) 567 8', received '+1 (234) 567 8-'
+1234567 // expected '+1 (234) 567', received '+1 (234) 567 -'
+123 // expected '+1 (23', received '+1 (23) -'
What am I missing here?
2
Answers
You can use a replacement function in your replace method. With this you can build your string based on your required conditions:
Off-topic: I was a little confused by your requirements. I think the replacements will make more sense:
Don’t reinvent the wheel. Look into Google’s LibPhonenumber, which has a javascript implementation and does ‘As you type’ formatting. You can try the demo here.
Output for your example:
This works for all (most?) countries and ensures you use a formatting that is globally used. If I’m not mistaken it is used in Android phones and most certainly in lots of other projects and I think it can be considered a de facto standard for formatting numbers.