let text = "testing: 1, 2, 3";
console.log(text.split(/D+/));
Output:
["", "1", "2", "3"]
why "testing:" is not the first element? "testing:" is also non-digit like space. What is the logic behind first element as empty string?
let text = "testing: 1, 2, 3";
console.log(text.split(/D+/));
Output:
["", "1", "2", "3"]
why "testing:" is not the first element? "testing:" is also non-digit like space. What is the logic behind first element as empty string?
4
Answers
To make it easier to understand:
The explanation: since the delimiter is found in the string so it definitely can split the string, despite of the result being 2 empty strings.
.split()
divides a string by removing the matching substrings.In your case:
Prefer to use match
It’s about how delimiters at the beginning or end of a string are handled.
First understand that
D+
matches the following strings intesting: 1, 2, 3
testing:
,
,
Those are now the delimiters. What’s before the first delimiter is
""
and what’s after the last delimiter is3
When the delimiter is at the beginning or end of a string, then split will return an empty element before the initial delimiter or after the final delimeter.
Refer to the documentation
This is important because if you had a data file with name, street in comma-separated value (CSV) format and you split a line that looked like
,main
you would expect that name =""
and street =main
. "Where the street has no name." 😉