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

后端 未结 8 1539
耶瑟儿~
耶瑟儿~ 2020-12-11 01:58

Really, pretty much what the title says.

Say you have this string:

var theString = \"a=b=c=d\";

Now, when you run theString

8条回答
  •  半阙折子戏
    2020-12-11 02:36

    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.

提交回复
热议问题