Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript improve regex to match number chunks of 3

I want to get a number chunks of 3 if i could by example if i have the number 22345678 i want to get ['22','345','678']. Using the following regex

/(\d{1,3})(?=(\d{3})+(?!\d))/g

I get ['22','345']

Anyone can help me to improve my regex?

An example in here --> https://regex101.com/r/cF6rN4/1 and a snippet in this post

console.log('22345678'.match(/(\d{1,3})(?=(\d{3})+(?!\d))/g));
like image 929
Gonzalo Pincheira Arancibia Avatar asked Dec 06 '25 06:12

Gonzalo Pincheira Arancibia


1 Answers

Match strings which are followed by digits of length as 3's multiplier or at the end.

console.log('22345678'.match(/\d{1,3}(?=(\d{3})+$|$)/g));

Regex explanation here.

Regular expression visualization


You can avoid the capturing group since it's not necessary.

/\d{1,3}(?=(?:\d{3})+$|$)/g
//---------^^^-------------

UPDATE : It can be much more simplified by using *(0 or more repetition) instead of +(1 or more repetition) which helps to avoid the pipe symbol. As @torazaburo's comment both (\d{3})*$ and (\d{3})+$|$ are equivalent.

/\d{1,3}(?=(\d{3})*$)/g
like image 171
Pranav C Balan Avatar answered Dec 07 '25 21:12

Pranav C Balan



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!