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');
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.
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 .
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.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With