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?