I want to split a string into parts with a defined length. This means if I have a given string like "1234567890"
and want to split it in parts with length 3
then I expect the result ["123", "456", "789", "0"]
. To achive this I have found a solution here: https://stackoverflow.com/a/14349616/2577116
Now, I also want to split not starting at the beginning but at the end of the string. The expected result would be ["1", "234", "567", "890"]
.
Therefore I used and modified the solution above and came up with this:
function (str, len, reversed) {
//create array from string
var _parts = str.split(""),
_size = Math.ceil(_parts.length/len),
_ret = [],
_offset;
//should give ["123", "456", "789", "0"]
if (!reversed) {
for (var _i=0; _i<_size; _i++) {
_offset = _i * len;
_ret[_i] = _parts.slice(_offset, _offset+len).join("");
}
}
//should give ["1", "234", "567", "890"]
else {
//reverse input
_parts.reverse();
//apply same algorithm as above but don't join yet
for (var _j=0; _j<_size; _j++) {
_offset = _j * len;
_ret[_j] = _parts.slice(_offset, _offset+len);
}
//bring each subitem back to right order, join
_ret.forEach(function (item, i) {
_ret[i] = item.reverse().join("");
});
//reorder items
_ret.reverse();
}
return _ret;
}
This seems to work pretty well. I'm asking for some better/simplified solution as mine feels a little bulky.