Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string, at every nth position, with JavaScript? [duplicate]

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.

like image 662
Lucas Avatar asked Oct 02 '12 08:10

Lucas


3 Answers

Try the below code:

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

For nth position:

foo.match(new RegExp('.{1,' + n + '}', 'g'));
like image 76
xdazz Avatar answered Oct 18 '22 15:10

xdazz


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/

like image 33
sp00m Avatar answered Oct 18 '22 14:10

sp00m


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));
like image 7
freefaller Avatar answered Oct 18 '22 14:10

freefaller