Reputation: 4167
I have read many answers on stackoverflow but , unable to find the solution.
Let say we have a string 'Hello World'
. The idea is to split Hello World
into equal parts.
Example:
'he','ll', 'ow', 'or','ld'
The string can be of N characters and each time, the string has to be split of equal substrings.
Incase of hello World
we had hello worlds
the split strings would be,
'he','ll', 'ow', 'or','ld', 's'
Note that there is no N supplied on which the string can be divided into. The N here is dynamic based on the string supplied. So N can be 2,3,4...N, depending on the string size.
Upvotes: 1
Views: 400
Reputation: 386624
You could give the length of the substrings and iterate until the end of the adjusted string.
function split(string, size) {
var splitted = [],
i = 0;
string = string.match(/\S+/g).join('');
while (i < string.length) splitted.push(string.slice(i, i += size));
return splitted;
}
console.log(...split('Hello World', 2));
console.log(...split('Hello Worlds', 2));
Upvotes: 1