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

后端 未结 18 927
有刺的猬
有刺的猬 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:37

    Hi there i had the same problem wanted to split only several times, couldnt find anything so i just extended the DOM - just a quick and dirty solution but it works :)

    String.prototype.split = function(seperator,limit) {
        var value = "";
        var hops  = [];
    
        // Validate limit
        limit = typeof(limit)==='number'?limit:0;
    
        // Join back given value
        for ( var i = 0; i < this.length; i++ ) { value += this[i]; }
    
        // Walkthrough given hops
        for ( var i = 0; i < limit; i++ ) {
            var pos = value.indexOf(seperator);
            if ( pos != -1 ) {
                hops.push(value.slice(0,pos));
                value = value.slice(pos + seperator.length,value.length)
    
            // Done here break dat
            } else {
                break;
            }
        }
        // Add non processed rest and return
        hops.push(value)
        return hops;
    }
    

    In your case would look like that

    >>> "Split this, but not this".split(' ',2)
    ["Split", "this,", "but not this"]
    

提交回复
热议问题