Regular Expression to reformat a US phone number in Javascript

后端 未结 13 2218
眼角桃花
眼角桃花 2020-12-02 07:32

I\'m looking to reformat (replace, not validate - there are many references for validating) a phone number for display in Javascript. Here\'s an example of some of the data:

13条回答
  •  醉梦人生
    2020-12-02 08:35

    This answer borrows from maerics' answer. It differs primarily in that it accepts partially entered phone numbers and formats the parts that have been entered.

    phone = value.replace(/\D/g, '');
    const match = phone.match(/^(\d{1,3})(\d{0,3})(\d{0,4})$/);
    if (match) {
      phone = `${match[1]}${match[2] ? ' ' : ''}${match[2]}${match[3] ? '-' : ''}${match[3]}`;
    }
    return phone
    

提交回复
热议问题