Gonzalo Pincheira Arancibia Gonzalo Pincheira Arancibia - 4 months ago 15
Javascript Question

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));




Answer

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