Is there a way to split a string by some symbol but only at first occurrence?
Example: date: '2019:04:01'
should be split into date
and '2019:04:01'
It could also look like this date:'2019:04:01'
or this date : '2019:04:01'
and should still be split into date
and '2019:04:01'
string.split(':');
I tried using the split()
method. But it doesn't have a limit attribute or something like that.
Dart Split String You can split a string with a substring as delimiter using String. split() method. The function returns a list of strings.
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 .
split method Null safety const string = 'Hello world! '; final splitted = string. split(' '); print(splitted); // [Hello, world!]; If the pattern doesn't match this string at all, the result is always a list containing only the original string.
You were never going to be able to do all of that, including trimming whitespace, with the split command. You will have to do it yourself. Here's one way:
String s = "date : '2019:04:01'";
int idx = s.indexOf(":");
List parts = [s.substring(0,idx).trim(), s.substring(idx+1).trim()];
You can split the string, skip the first item of the list created and re-join them to a string.
In your case it would be something like:
var str = "date: '2019:04:01'";
var parts = str.split(':');
var prefix = parts[0].trim(); // prefix: "date"
var date = parts.sublist(1).join(':').trim(); // date: "'2019:04:01'"
The trim methods remove any unneccessary whitespaces around the first colon.
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