Reputation: 273
Thanks in advance for taking the time to read. I am a total beginner and I know this might sound one of those "help me understand this" questions but I'm sorry if that was the case and I'll try to be specific as much as I can.
Basically I need to create a function to chop strings into smaller strings of input length, I have tried array methods but for some reason I keep getting an empty array. So that the if the input string is "hell" and the input length is 2 the output would be ["he","ll]
Also, in relevance to this problem, I was wondering if you can set a for loop condition x.length<=0.
Here is my code:
function chop(a, b) {
// a = "hell"
// b = 2
var ans = [];
var x = a.split(""); // [h,e,l,l]
for (var i = 0; i<=(x.length/b); i++) {
// condition i<=2
// I was also wondering how can set the condition to be x.length <= 0
x = x.slice(0,(b-1)); // x = "he"
ans.push(x); // ans = ["he", ]
x = x.splice(0,b); // x = [l,l]
}
console.log(ans);
}
Upvotes: 1
Views: 46
Reputation: 288020
It's simple if you use regular expressions:
"hello".match(/.{1,2}/g) || []; // ["he", "ll", "o"]
However, if you don't know the value of the second parameter beforehand, it's a bit more dirty:
function chop(a, b) {
return a.match(new RegExp('.{1,'+b+'}','g')) || [];
}
chop("hello", 2); // ["he", "ll", "o"]
In that case, it would be a good idea to sanitize b
before inserting it in the regex.
Upvotes: 2
Reputation: 5953
You can do it like this:
function chop(a, b) {
var ans = [];
for (var i = 0; i < a.length; i += b) {
ans.push(a.substring(i, i + b));
}
console.log(ans);
}
chop("hello", 2); //logs ["he", "ll", "o"]
Upvotes: 2