Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for inserting - after specific indexes in a number

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?

like image 570
Learner Avatar asked Nov 04 '25 02:11

Learner


1 Answers

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 digits

The $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-") 
);
like image 175
Wiktor Stribiżew Avatar answered Nov 06 '25 19:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!