Skip to content

Instantly share code, notes, and snippets.

As per [MDN][1] 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.