For the desired output, we need to use substring, since the smaller section is taken at beginning than at end. Note: we do not use slice, because negative index in slice will take characters from string from end again. So, we stick with substring to avoid that.
var str = "abcdefgh";
var len = str.length;
var res = [];
for(var i=len;i>0;i=i-3){
res.push(str.substring(i-3,i));
}
//res array will contain the desired output now
But, if parsing should be greedy form beginning, i.e. {3,3,2} instead of {2,3,3} then, use the regex (/[a-zA-Z]{1,3}/gi
) for this,which is easier and faster.For this we do not need substring.
var str = "abcdef";
var result = str.match(/[a-zA-Z]{1,3}/gi); //["abc","def"]
var str = "abcdefgh";
var result = str.match(/[a-zA-Z]{1,3}/gi); //["abc","def","gh"]
var str = "abcdefg";
var result = str.match(/[a-zA-Z]{1,3}/gi); //["abc","def","g"]
String.prototype.split
with a regular expression, or loop and count characters.