Split a string only the at the first n occurrences of a delimiter

后端 未结 18 812
有刺的猬
有刺的猬 2020-12-24 06:22

I\'d like to split a string only the at the first n occurrences of a delimiter. I know, I could add them together using a loop, but isn\'t there a more straight forward appr

18条回答
  •  有刺的猬
    2020-12-24 06:52

    Yet another implementation I just wrote:

    export function split(subject, separator, limit=undefined, pad=undefined) {
        if(!limit) {
            return subject.split(separator);
        }
        if(limit < 0) {
            throw new Error(`limit must be non-negative`);
        }
        let result = [];
        let fromIndex = 0;
        for(let i=1; i

    Doesn't use regexes, nor does it over-split and re-join.

    This version guarantees exactly limit elements (will pad with undefineds if there aren't enough separators); this makes it safe to do this kind of ES6 stuff:

    let [a,b,c] = split('a$b','$',3,null);
    // a = 'a', b = 'b', c = null
    

提交回复
热议问题