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

后端 未结 18 891
有刺的猬
有刺的猬 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: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"]
    

提交回复
热议问题