As per MDN when using a regular expression for splitting a string and the regex contains groups, the groups are included in the result (whereas the matched part would normally be discarded). I.e. you get ['before-match', 'matched group', after-match']
. Also, matches at the beginning of a string result in an empty string as first entry in the results array.
[emptyBecauseMatchAtStart, group, rest] = '<=asdf'.split(/(<=|>=|<|>)/)
The second is a bit counter-intuitive:
'<=asdf'.split(/(<=)|(>=)|<|>/) // results in ["", "<=", undefined, "asdf"]
The empty string, "<="
and "asdf"
are clear. The undefined
is a result of the second group (>=)
not matching anything.
The last example is of course a bit weird as regexes with nested groups often are. Here is speculation on my part how this comes:
'<=asdf'.split(/((<=)|(>=)|(<)|(>))/)
[
"", //match at start of string
"<=", // (<=) group
"<=", // ((<=)|...) group
undefined, // (>=) group
undefined, // (<) group *
undefined, // (>)
"asdf" //rest of string
]
- From a simple test:
"asdfasdf".split(/(as)|(asdf)/)
if a group matches the string is cut and the split applied to the rest. Therefore the (<) group does no longer match.