3

So I have a string that I need to split into an array, for example:

"1234567890"

I need to be able to split it like:

"1234567890".break(2) = ["12345", "67890"]

and:

"1234567890".break(3) = ["123", "456","7890"]

So I don't want it to split it into an array of equal parts, I want to split the string into an array of length n. How do you think I would go about doing this?

No, its not this: regex - Split large string in n-size chunks in JavaScript

Community
  • 1
  • 1
Kitsumi
  • 41
  • 7

2 Answers2

2

That's exactly what you asked

function breakString(str, items) {
  var result = str.match(new RegExp('.{1,' + Math.floor(str.length / items) + '}', 'g'));

  while(result.length > items) {
    result[result.length - 2] += result[result.length - 1];
    result.splice(result.length - 1, 1);
  }

  return result;
}
Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50
1

This function does the job:

var brk = function(s,n){
    if(s.split && typeof n === "number") {
        var l = s.length,
            z = ~~(l/n),
            zx = (z*n<l) ? l-z*(n-1) : z;
            a = [];

        for(var i=0; i<n-1; i++) {
            a[i] = s.slice(i*z,i*z+z);
        }

        a[Math.ceil(n-1)] = s.slice(-zx);

        return a;
    } else {
        return false;
    }
};

You can test it with a console log:

console.log(brk("1234567890",3));
Arman Ozak
  • 2,304
  • 11
  • 11