I am doing:
"b::::c:::".split(':')
Result:
["b", "", "", "", "c", "", ""] # expect
["b", "", "", "", "c"] # actual
What is the problem here? how can i get what i expected.
If the delimiter is an empty string, the split() method will return an array of elements, one element for each character of string. If you specify an empty string for string, the split() method will return an empty string and not an array of strings.
Using split()If the string and separator are both empty strings, an empty array is returned.
To split a string and remove the empty elements from the array, call the split() method on the string to get an array of substrings and use the filter() method to filter out any empty elements from the array, e.g. str. split(' ').
There's a limit
parameter to .split(pattern=$;, [limit])
. If limit
is omitted, trailing null fields are suppressed. You need to provide a negative limit
"b::::c:::".split(':', -1)
but bear in mind that this will return three ""
values at the end of the array.
result: ["b", "", "", "", "c", "", "", ""]
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