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

后端 未结 8 1541
耶瑟儿~
耶瑟儿~ 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:41

    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.

提交回复
热议问题