0

I have looked into this problem, but I couldn't find a good answer. So here is my code:

var str = '000100111000010110'
var length = 2;
var temp = new Array(str.match(/.{length}/g));

But this doesn't work.

It's very important to keep the length of a variable, and if I don't have to, I won't use a regular expression.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Attila Herbert
  • 309
  • 1
  • 2
  • 10

1 Answers1

2

Just use a regular for loop and substr. No need to involve regex where it isn't needed:

var str = '000100111000010110';
var length = 2;

var split = [];
for (var i = 0; i < str.length; i += length) {
    split.push(str.substr(i, length));
}

console.log(split);
// ["00", "01", "00", "11", "10", "00", "01", "01", "10"]
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102