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

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

    Although you can give split a limit, you won't get back what you've said you want. Unfortunately, you will have to roll your own on this, e.g.:

    var string = 'Split this, but not this';
    var result = string.split(' ');
    
    if (result.length > 3) {
        result[2] = result.slice(2).join(' ');
        result.length = 3;
    }
    

    But even then, you end up modifying the number of spaces in the latter parts of it. So I'd probably just do it the old-fashioned write-your-own-loop way:

    function splitWithLimit(str, delim, limit) {
      var index,
          lastIndex = 0,
          rv = [];
    
      while (--limit && (index = str.indexOf(delim, lastIndex)) >= 0) {
        rv.push(str.substring(lastIndex, index));
        lastIndex = index + delim.length;
      }
      if (lastIndex < str.length) {
        rv.push(str.substring(lastIndex));
      }
      return rv;
    }
    

    Live copy

    0 讨论(0)
  • 2020-12-24 06:36

    The JavaScript ".split()" function already accepts a second parameter giving the maximum number of splits to perform. However, it doesn't retain the tail end of your original string; you'd have to glue it back on.

    Another approach would be to iteratively shave off a leading portion of the string with a regex, stopping when you've gotten your limit.

    var str = "hello out there cruel world";
    var parts = [];
    while (parts.length < 3) { // "3" is just an example
      str = str.replace(/^(\w+)\s*(.*)$/, function(_, word, remainder) {
        parts.push(word);
        return remainder;
      });
    }
    parts.push(str);
    

    edit — and it just occurs to me that another simple way would be to just use plain ".split()", pluck off the first few parts, and then just ".slice()" and ".join()" the rest.

    0 讨论(0)
  • 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"]
    
    0 讨论(0)
  • 2020-12-24 06:38
    var s='Split this, but not this', a=s.split(','), b=a[0].split(' ');
    b.push(a[1]);
    alert(b);
    

    alerts ['Split', 'this', 'but not this']

    0 讨论(0)
  • 2020-12-24 06:39

    Using Array.slice:

    function splitWithTail(str,delim,count){
      var parts = str.split(delim);
      var tail = parts.slice(count).join(delim);
      var result = parts.slice(0,count);
      result.push(tail);
      return result;
    }
    

    Results:

    splitWithTail(string," ",2)
    // => ["Split", "this,", "but not this"]
    
    0 讨论(0)
  • 2020-12-24 06:40

    Combination of split and join with ES6 features does this pretty neat:

    let [str1, str2, ...str3] = string.split(' ');
    str3 = str3.join(' ');
    
    0 讨论(0)
提交回复
热议问题