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.
As you have asked (om 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;
}
splitNChars("foofaafoofaafoofaafoofaafoofaa",3);
You can do like this:
var input = "foofaafoofaafoofaafoofaafoofaa";
var result = [];
while (input.length) {
result.push(input.substr(0, 3));
input = input.substr(3);
}
As Mark Walter has pointed out, this solution from another Stack Overflow question works perfectly:
function splitStringAtInterval (string, interval) {
var result = [];
for (var i=0; i<string.length; i+=interval)
result.push(string.substring (i, i+interval));
return result;
}
The function followed by an example using it. The example test outputs: ["abc","def","ghi","j"]
function splitEvery(str, n)
{
var arr = new Array;
for (var i = 0; i < str.length; i += n)
{
arr.push(str.substr(i, n));
}
return arr;
}
var result = splitEvery('abcdefghij', 3);
document.write(JSON.stringify(result));
©2020 All rights reserved.