Regular Expression to reformat a US phone number in Javascript

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

    Almost all of these have issues when the user tries to backspace over the delimiters, particularly from the middle of the string.

    Here's a jquery solution that handles that, and also makes sure the cursor stays in the right place as you edit:

    //format text input as phone number (nnn) nnn-nnnn
    $('.myPhoneField').on('input', function (e){
        var $phoneField = e.target;
        var cursorPosition = $phoneField.selectionStart;
        var numericString = $phoneField.value.replace(/\D/g, '').substring(0, 10);
    
        // let user backspace over the '-'
        if (cursorPosition === 9 && numericString.length > 6) return;
    
        // let user backspace over the ') '
        if (cursorPosition === 5 && numericString.length > 3) return;
        if (cursorPosition === 4 && numericString.length > 3) return;
    
        var match = numericString.match(/^(\d{1,3})(\d{0,3})(\d{0,4})$/);
        if (match) {
            var newVal = '(' + match[1];
            newVal += match[2] ? ') ' + match[2] : '';
            newVal += match[3] ? '-' + match[3] : '';
    
            // to help us put the cursor back in the right place
            var delta = newVal.length - Math.min($phoneField.value.length, 14);      
            $phoneField.value = newVal;
            $phoneField.selectionEnd = cursorPosition + delta;
        } else {
            $phoneField.value = '';        
        }
    })
    
    0 讨论(0)
提交回复
热议问题