Reputation: 9131
I've got this regex:
([a-z]+)(?:\.)
.
Using it in Javascript like this:
"test.thing.other".split(/([a-z]+)(?:\.)/);
ends up giving me an array like this:
["", "test", "", "thing", "other"]
.
I have no idea why the first and third elements are being put into that array. Can anyone show me what I'm doing wrong?
Upvotes: 4
Views: 53
Reputation: 784998
Based on your question and comment "Capture a-z until a period" I believe you should be rather using String.match like this:
arr = "test.thing.other".match(/[a-z]+(?=\.)/g);
gives:
["test", "thing"]
Upvotes: 3
Reputation: 545528
The parentheses are the reason. Here’s what MDN says on string.split
says:
If
separator
is a regular expression that contains capturing parentheses, then each time separator is matched the results (including any undefined results) of the capturing parentheses are spliced into the output array.
They also caution:
However, not all browsers support this capability.
So this result may be inconsistent. If you just want to split by the content of the expression, remove the parentheses:
>> 'test.thing.other'.split(/[a-z]+\./)
["", "", "other"]
Which may also not be what you want, but is the intuitively expected result given your expression.
If you want to split by dot then you need to provide exactly that in the regular expression: a dot.
>> 'test.thing.other'.split(/\./)
["test", "thing", "other"]
Upvotes: 2