skip to Main Content

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;
}

Here is the output

All the code is working fine except when 1 put at front

2

Answers


  1. Chosen as BEST ANSWER

    I was starting from substring 0 instead of 1.


  2. 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.

    const MIN_PHONE_LENGTH = 10;
    
    const phoneNumberFormatter = (num) => {
      const d = num.trim().replace(/D/g, ''); // Digits
      if (d.length === 0) {
        return '';
      }
      const o = d.length - MIN_PHONE_LENGTH; // Delta or offset 
      if (o > 0) {
        return `+${d.slice(0, o)} (${d.slice(o, o + 3)}) ${d.slice(o + 3, o + 6)}-${d.slice(o + 6, o + 10)}`;
      }
      return `(${d.slice(0, 3)}) ${d.slice(3, 6)}-${d.slice(6, 10)}`; // Default
    }
    
    function formatPhoneNumber({ target }) {
      target.value = phoneNumberFormatter(target.value);
    }
    
    formatPhoneNumber({ target: document.querySelector('#phone') }); // Init
    <!-- +1 (456) 785-3424 -->
    <input type="text" id="phone" oninput=formatPhoneNumber(event) value="4567853424" />
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search