Separate string into array of strings every n characters reverse and reversing back

I’m trying to format a large number, which is a String, into a locale’s format. toLocaleString() or anything similar won’t work, I have to do this manually. Forget replacing a . with a , for the moment, I just want to separate the number into chunks of 3 (like chunks of thousands). I’m trying to do this by reversing the String, splitting it into an array every 3 characters, and reversing back.

const chunkByThree = (input) => {
  let chunkedInput = input.split('').reverse().join('').match(/.{1,3}/g);
  chunkedInput = chunkedInput.reverse();

  return chunkedInput;

However, let’s take a large number, like '1243525152519'. It should be separated into ['1', '243', '525', '152', '519'] but because reverse() only affects the order of the array’s elements and not the values themselves, the function will return [ '1', '342', '525', '251', '915' ] when reversing it back (line 3). How can I correctly reverse it back, by also reversing the strings inside each array value aside from the order of the array’s elements?


You could consume the digits from an array using splice, lopping off 3 from the end on each iteration. If there are fewer than 3 digits left you’ll get whatever remains (the remaining 1 or 2 digits).

(Using unshift allows you to keep the chunks in the correct order by pushing into the start of the array instead of appending to the end.)

Then you can reassemble the chunks with join. No regex or reversing required.

Something like this?

const num = '1243525152519';
const digits = num.split('');
const chunks = [];

while(digits.length) { // as long as we have more digits…
  // …lop off the last three and stringify them,
  // push it into the start of the chunks array:

// then reassemble the chunks with your preferred delimiter
const result = chunks.join(',') // join the chunks
console.log(result); // voila