I have the following string:
foofaafoofaafoofaafoofaafoofaa
An array with 10 rows (if I split by every 3rd character, that is), which looks something like this, if I were to instantiate it:
var fooarray = new Array ('foo', 'faa', 'foo', 'faa', 'foo', 'faa', 'foo', 'faa', 'foo', 'faa');
So I want a function, either built-in or custom-made, which can help me split up a string by every nth character.
Try the below code:
var foo = "foofaafoofaafoofaafoofaafoofaa";
console.log( foo.match(/.{1,3}/g) );
For nth position:
foo.match(new RegExp('.{1,' + n + '}', 'g'));
var s = "foofaafoofaafoofaafoofaafoofaa";
var a = [];
var i = 3;
do{ a.push(s.substring(0, i)) }
while( (s = s.substring(i, s.length)) != "" );
console.log( a )
Prints:
foo,faa,foo,faa,foo,faa,foo,faa,foo,faa
Working demo: http://jsfiddle.net/9RXTW/
As I was writing this, @xdazz came up with the wonderfully simple regex solution.
But as you have asked (on the comments to that answer) for a non-regex solution, I will submit this anyway...
function splitNChars(txt, num) {
var result = [];
for (var i = 0; i < txt.length; i += num) {
result.push(txt.substr(i, num));
}
return result;
}
console.log(splitNChars("foofaafoofaafoofaafoofaafoofaa",3));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With