Regular Expression to reformat a US phone number in Javascript

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

    I'm using this function to format US numbers.

    function formatUsPhone(phone) {
    
        var phoneTest = new RegExp(/^((\+1)|1)? ?\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})( ?(ext\.? ?|x)(\d*))?$/);
    
        phone = phone.trim();
        var results = phoneTest.exec(phone);
        if (results !== null && results.length > 8) {
    
            return "(" + results[3] + ") " + results[4] + "-" + results[5] + (typeof results[8] !== "undefined" ? " x" + results[8] : "");
    
        }
        else {
             return phone;
        }
    }
    

    It accepts almost all imaginable ways of writing a US phone number. The result is formatted to a standard form of (987) 654-3210 x123

提交回复
热议问题