0

I need to split a long string in chunks of, say, 3 or 4 characters, but starting from the end. The problem I have is that I can't obtain the last chun k (or first characters from the string) when its length is not a multiple of the size of the chunks.

My code is:

var str ="890123456789";
var newstr="";
for(var i = 1; i<=(str.length/4)+1;i++) {

    if(i==(str.length/4)+1) 
      res = str.substr(-4*i,4); 
    else
      var res = str.substr(-4*i,4);  

    newstr = res+"."+newstr;

  }

If the string length is a multiple of 4 in this case i obtain in newstr:

8901.2345.6789

But if it has some extra character the last element picked becomes weird:

7890.8901.2345.6789

And I need something like:

7.8901.2345.6789

What am I doing wrong?

Ikzer
  • 527
  • 11
  • 29
  • See the linked question, just use `.` instead of `,`. – T.J. Crowder Jan 03 '20 at 12:21
  • *"If the string length is a multiple of 4 in this case i obtain in `newstr`: `"8901.2345.6789"`"* [Not with the code above](https://jsfiddle.net/tjcrowder/5k7y0xv2/), it sets `newstr` to `"89.890.234.678."`. – T.J. Crowder Jan 03 '20 at 12:22

0 Answers0