Javascript Regular Expression to add dash after every 3rd and 4th characters
Solution 1
How about
> "12345678".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-78"
> "123456789".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-789"
> "1234567890".match(/\d{3}(?=\d{2,3})|\d+/g).join("-")
"123-456-7890"
Solution 2
Do you need to use regular expressions for everything or would maybe something like this also help you out?
function convertToValidPhoneNumber(text) {
var result = [];
text = text.replace(/[^\d]/g,"");
while (text.length >= 6) {
result.push(text.substring(0, 3));
text = text.substring(3);
}
if(text.length > 0) result.push(text);
return result.join("-");
}
You could use this function everytime the text in your inputfield changes. It will produce the following results:
"12345678" -> "123-45678"
"123d456789" -> "123-456-789"
"123-4567-89" -> "123-456-789"
GGio
Updated on June 18, 2022Comments
-
GGio almost 2 years
The following regex:
x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, "-");
adds dash after each 3rd character so entered
123456789
turns into123-456-789
. Im trying to use this regex to format phone number. The problem arises on the 10th character. So entered1234567890
turns into1-234-567-890
.How would I modify the above regex to turn strings that have 10 digits into
123-456-7890
. I use this regex because this happens as user is typing in uses keyup event.If you know easier or better way of doing this please help me out, dashes has to be added while user is typing in. No other characters allowed.
Notes:
- Cant use Jquery Masked input plugin (because if editing the middle character it's focus gets messed up)
-
GGio almost 11 yearsworks but If i remove/add digit from middle and add digit it does not reformat it. Example: "123-456-7890" added number 1 next to 5 gives result: "123-4516-7890" should not allow
-
georg almost 11 years@GGio: remove the dashes first
val=val.replace(/-/g,'')
and then reformat. -
Jaison James over 5 years123-4567890, Pls help me to get a result like this. Only insert hyphen after the first n digit
-
Zsolt Meszaros over 3 yearsWhy are you screaming on all your answers today? Please, edit your answer and use lowercase instead of UPPERCASE.
-
Hassan Qasim over 3 years@ZsoltMeszaros it's just because of caps, btw why is it important to write in lowercase?
-
Zsolt Meszaros over 3 yearsBecause messages typed completely in capital letters are equated to shouting and other argumentative behaviours.