Last Updated: December 26, 2018
· gaqzi

Javascript String.split that'll return the remainder

In other languages I use String.splits' limit argument usually means, "split this string this many times, and put any remainder as the last array index". In Javascript however anything past the limit split is just discarded.


 /* A function that splits a string `limit` times and adds the remainder as a final array index. 
  * > var a = 'convoluted.madeup.example';
  * > a.split('.', 1);
  * < ['convoluted']
  * // What I expected:
  * < ['convoluted', 'madeup.example']
function split(str, separator, limit) {
    str = str.split(separator);

    if(str.length > limit) {
        var ret = str.splice(0, limit);

        return ret;

    return str;

3 Responses
Add your response


splice changes the array in place, if it removes it'll return the items removed.

With the test cases I've had I've gotten out the results I want, so while I don't deny the possibility of a bug it's not in my current test cases.

Test cases being:
split('convoluted.madeup.example.with.more.stuff', '.', 1) => ["convoluted", "madeup.example.with.more.stuff"]
split("hello-do-nothing-with-me-except-an-array", '.', 1) => ["hello-do-nothing-with-me-except-an-array"]
split("first.second-but-also-the-remainder-even-if-more-mightve-been", '.', 3) =>
["first", "second-but-also-the-remainder-even-if-more-mightve-been"]

over 1 year ago ·

Haha, that's a very good catch. A really silly if there. :)

over 1 year ago ·

here is another implementation:
function split2(str, separator, limit) {
if (limit==0) return [str];
var a = str.split(separator, limit);
if(a.length == limit) {
let s = a.join(separator) + separator;
a.push( str.substr(s.length) );
return a;
return [str];

this way you don't have to split the entire string (in case it is huge), also shouldn't the function always return an array?

over 1 year ago ·