Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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 approach?

var string = 'Split this, but not this';     var result = new Array('Split', 'this,', 'but not this'); 
like image 333
nines Avatar asked Apr 07 '11 13:04

nines


People also ask

How do you split a string on the first occurrence of certain characters?

To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.

How do you split on the first occurrence?

Use the str. split() method with maxsplit set to 1 to split a string on the first occurrence, e.g. my_str. split('-', 1) . The split() method only performs a single split when the maxsplit argument is set to 1 .

How do you separate a string from a delimiter?

You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma-separated String on a comma, breaking a pipe-delimited String on a pipe, or splitting a pipe-delimited String on a pipe.


1 Answers

As per MDN:

string.split(separator, limit); 

Update:

var string = 'Split this, but not this',     arr = string.split(' '),     result = arr.slice(0,2);  result.push(arr.slice(2).join(' ')); // ["Split", "this,", "but not this"] 

Update version 2 (one slice shorter):

var string = 'Split this, but not this',     arr = string.split(' '),     result = arr.splice(0,2);  result.push(arr.join(' ')); // result is ["Split", "this,", "but not this"] 
like image 50
davin Avatar answered Sep 22 '22 16:09

davin