38

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.

Shannon Young
  • 1,536
  • 1
  • 17
  • 26
Lucas
  • 16,930
  • 31
  • 110
  • 182
  • 1
    There's an answer here that does just that (http://stackoverflow.com/questions/4017671/how-do-you-split-a-string-at-certain-character-numbers-in-javascript) – Mark Walters Oct 02 '12 at 08:25

6 Answers6

85

Try the below code:

var foo = "foofaafoofaafoofaafoofaafoofaa";
console.log( foo.match(/.{1,3}/g) );

For nth position:

foo.match(new RegExp('.{1,' + n + '}', 'g'));
vsync
  • 118,978
  • 58
  • 307
  • 400
xdazz
  • 158,678
  • 38
  • 247
  • 274
12

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/

vsync
  • 118,978
  • 58
  • 307
  • 400
sp00m
  • 47,968
  • 31
  • 142
  • 252
7

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));
freefaller
  • 19,368
  • 7
  • 57
  • 87
  • Also `array` doesnt make a good variable name. Even thought Javascript is case sensitive it might be confusing. – clentfort Oct 02 '12 at 08:30
4

You can do like this:

var input = "foofaafoofaafoofaafoofaafoofaa";

var result = [];
while (input.length) {
    result.push(input.substr(0, 3));
    input = input.substr(3);
}

Demo: http://jsfiddle.net/Guffa/yAZJ2/

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

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;
}
Community
  • 1
  • 1
Lucas
  • 16,930
  • 31
  • 110
  • 182
0

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));
sarahg
  • 83
  • 7