Skip to content

Instantly share code, notes, and snippets.

@t-animal
Created September 5, 2018 07:21
Show Gist options
  • Save t-animal/673d549aa564d61a21d660625e4c4875 to your computer and use it in GitHub Desktop.
Save t-animal/673d549aa564d61a21d660625e4c4875 to your computer and use it in GitHub Desktop.

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment