Regular Expression to reformat a US phone number in Javascript

后端 未结 13 2224
眼角桃花
眼角桃花 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:27

    I've extended David Baucum's answer to include support for extensions up to 4 digits in length. It also includes the parentheses requested in the original question. This formatting will work as you type in the field.

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

提交回复
热议问题