I've looked at the examples on SO, but none are really what I'm looking for.
My problem is that when a user continues to type, I try to add a space after the area code and next 3 numbers, and then a dash in-between the last 4 characters, but the country prefix disappears and the dashes disappear as well.
I'm looking for a final phone format of:
+1 999 999 99-99
- If the user types
9(or anything else other than1) into the empty field, then the result should be+1 9. - If the value is
+1 999and the user types in9, the result should be+1 999 9 - If value is
+1 999 999 99and the user types in9, the result should be+1 999 999 99-9 - If the value is
+1 999 999 99-9and the user clicks backspace, the result should be+1 999 999 99 - If the value is
+1 9and the user clicks backspace, the result should be''
Here's my attempt that I've got on JSFiddle.
const onKeyup = (e) => {
const input = document.getElementById('input');
const value = input.value;
let _value = value;
if (_value.length === 1) {
_value = `+1 (${value}`;
} else {
_value.replace(
/(\d{1,2})(\d{1})?(\d{1,2})?(\d{1,4})?/,
function(_, p1, p2, p3, p4) {
let output = ""
if (p1) output = `${p1}`;
if (p2) output += `${p2}`;
if (p3) output += ` ${p3}-`
if (p4) output += ` ${p4}`
_value = output;
}
);
}
input.value = _value
}