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?