Auto Format Phone Number in Jquery

后端 未结 6 2144
Happy的楠姐
Happy的楠姐 2020-12-15 10:20

I have one textbox for phone number. My phone number should be XXX-XXX-XXX like this format.

I got the solution for XXX-XXX-XXX format, but i don\'t know how to modi

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-15 10:43

    For the formatting XXX-XXX-XXXX here is a simple solution:

    if(this.value.trim().length <= 8){
        this.value = this.value.replace(/(\d{3})\-?/g,'$1-');
     }
    

    Here is an example and you not need any framework or library or npm:

    this.phone.addEventListener('keyup', event => {
    
            if(this.phone.value.trim().length <= 8){
                this.phone.value = this.phone.value.replace(/(\d{3})\-?/g,'$1-');
            }
        }
    

    You could also do this if you like:

     this.phone.addEventListener('keyup', event => {
    
            if(this.phone.value.trim().length <= 8){
                this.phone.value = this.phone.value.replace(/(\d{3})\-?/g,'$1-');
            }else{
                this.phone.value = this.phone.value.replace(/(\d{4})\-?/g,'$1');
            }
        }
    

    Replace this this.phone with your value. I hope this helps.

提交回复
热议问题