I want to the number to be in US format +1 (456) 785 -3424
. But when I add 1
in front it is printed again and again
function numberReg(event) {
let input = event.target.value.replace(/[^0-9]/g, "");
let NumValue = "";
if (input.length >= 1) {
NumValue += "+1 ";
if (input.length >= 4) {
NumValue += "(" + input.substring(0, 3) + ") ";
if (input.length >= 7) {
NumValue += input.substring(3, 6) + " -" + input.substring(6, 10);
} else {
NumValue += input.substring(3, 6);
}
} else {
NumValue += input.substring(0, 3);
}
}
event.target.value = NumValue;
}
All the code is working fine except when 1 put at front
2
Answers
I was starting from substring 0 instead of 1.
You could format the number two ways.
If the length of the number is less than 11, default to a simple "(xxx) xxx-xxxx" format. Else, format with the country code at the beginning, accounting for the offset.