I am trying to insert '-' in a number. I want to insert this after the 3rd and the 7th letter.
For eg. Number : 123456789
Required Number : 123-4567-89
What I tried so far :
if (!Number.isNaN(value)) {
val = value.match(/\d{3}(?=\d{2,3})|\d+/g).join('-');
}
This gives me the result '-' after every third occurrence and not the required one[i.e. 123-456-789]. Can some regex expert help with this one?
Use
val = value.replace(/^(\d{3})(\d{4})/, "$1-$2-")
See the regex demo
Details
^ - start of string(\d{3}) - Capturing group 1: three digits(\d{4}) - Capturing group 2: four digitsThe $1 stands for the Group 1 value (the first 3 digits) and the $2 stands for the Group 2 value (the next 4 digits).
JS demo:
console.log(
"123456789".replace(/^(\d{3})(\d{4})/, "$1-$2-")
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With