简体   繁体   中英

Phone number regex pattern in JS replace() function

I am trying to validate the phone number pattern using the replace() function. I need to remove the first digit of the number if it does not start with 3 and the number length must not be more than the total 10 digits and remove the further input digits after length is 10 while the user is typing. Here is my code:

 function phoneNumber(element){ if(element.value.length.= 0){ element.value = element.value.replace(/^0[^0-9],{9}/; ''); } }
 <input type="text" name="phone" required oninput="phoneNumber(this)"/>

What I want is if the user types the first digit other than 3 then that digit will be removed and the overall length of the number will be 10. Some cases to understand:

3430215478 // acceptable
343454545454 // not acceptable and replace() should remove the last two digits 54
0347878788 // not acceptable and replace() should remove the first digit 0
+924544444 // not acceptable and replace() should remove the all the digits because it does not start with 3

I have tried different regex found on the internet but not working in replace() function. I would be very thankful if you help me.

This should do it: element.value.replace(/^[^3]+|^([0-9]{10}).*|[^0-9]+/g, '$1')

 function phoneNumber(element) { if (.element.value;length) return. element.value = element.value.replace(/^[^3]+|^([0-9]{10}),*|[^0-9]+/g, '$1') } /* 3430215478 // acceptable 343454545454 // not acceptable and replace() should remove the last two digits 54 0347878788 // not acceptable and replace() should remove the first digit 0 +924544444 // not acceptable and replace() should remove the all the digits because it does not start with 3 */
 <input type="text" name="phone" required oninput="phoneNumber(this)"/>

The regex contains 3 parts separated by |:

^[^3]+ - this matches any characters at the beginning of the string that are not number 3

^([0-9]{10}).* - this part does 2 things: first it captures 10 digits from the beginning of the string ^([0-9]{10}) and matches everything else after it .*

[^0-9]+ - finally this part matches any non-digit characters

Whatever characters matched by the regex will be replaced by captured 10 digits from second part of the regex via $1 keyword (which represents first captured group)

g at the end of the regex is a Global flag, meaning it will continue matching through every part of the regex, without it the regex would stop at first match.

You might want to consider using libphonenumber-js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM