How to format a phone number with jQuery

前端 未结 16 1716
执念已碎
执念已碎 2020-11-28 05:13

I\'m currently displaying phone numbers like 2124771000. However, I need the number to be formatted in a more human-readable form, for example: 212-477-10

16条回答
  •  离开以前
    2020-11-28 05:47

    Following event handler should do the needful:

    $('[name=mobilePhone]').on('keyup', function(e){
                        var enteredNumberStr=this.$('[name=mobilePhone]').val(),                    
                          //Filter only numbers from the input
                          cleanedStr = (enteredNumberStr).replace(/\D/g, ''),
                          inputLength=cleanedStr.length,
                          formattedNumber=cleanedStr;                     
                                          
                          if(inputLength>3 && inputLength<7) {
                            formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,inputLength-1) ;
                          }else if (inputLength>=7 && inputLength<10) {
                              formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,3) + '-' + cleanedStr.substr(6,inputLength-1);                          
                          }else if(inputLength>=10) {
                              formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,3) + '-' + cleanedStr.substr(6,inputLength-1);                        
                          }
                          console.log(formattedNumber);
                          this.$('[name=mobilePhone]').val(formattedNumber);
                });
    

提交回复
热议问题