Limiting the times that .split() splits, rather than truncating the resulting array

If you want the exact equivalent of the Java implementation (no error checking or guard clauses etc):

function split(str, sep, n) {
    var out = [];

    while(n--) out.push(str.slice(sep.lastIndex, sep.exec(str).index));

    out.push(str.slice(sep.lastIndex));
    return out;
}

console.log(split("a=b=c=d", /=/g, 2)); // ['a', 'b', 'c=d']

This has the added benefit of not computing the complete split beforehand, as you mentioned in your question.


I'd use something like this:

function JavaSplit(string,separator,n) {
    var split = string.split(separator);
    if (split.length <= n)
        return split;
    var out = split.slice(0,n-1);
    out.push(split.slice(n-1).join(separator));
    return out;
}

What we're doing here is:

  1. Splitting the string entirely
  2. Taking the first n-1 elements, as described.
  3. Re-joining the remaining elements.
  4. Appending them to the array from step 2 and returning.

One might reasonably think you could chain all of those calls together, but .push() mutates an array rather than returning a new one. It's also a bit easier for you to follow this way.


One more possible implementation:

function split(s, separator, limit) {
  // split the initial string using limit
  var arr = s.split(separator, limit);
  // get the rest of the string...
  var left = s.substring(arr.join(separator).length + separator.length);
  // and append it to the array
  arr.push(left);
  return arr;
}

Fiddle is here.