Preview:
// Example 4051231234 -> (405) 123-1234
export const formatToUSPhoneNumber = (e: React.ChangeEvent<HTMLInputElement>): string => {
  const phoneField = e.target;

  const cursorPosition = phoneField.selectionStart;
  const numericString = phoneField.value.replace(/\D/g, '').substring(0, 10);

  const match = numericString.match(/^(\d{1,3})(\d{0,3})(\d{0,4})$/);

  if (match) {
    let newVal = '(' + match[1];
    newVal += match[2] ? ') ' + match[2] : '';
    newVal += match[3] ? '-' + match[3] : '';

    // to help us put the cursor back in the right place
    const delta = newVal.length - Math.min(phoneField.value.length, 14);
    phoneField.value = newVal;
    if (cursorPosition) {
      phoneField.selectionEnd = cursorPosition + delta;
    }
  } else {
    phoneField.value = '';
  }

  return phoneField.value;
};
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter