Why do string.split() results include undefined?

Viewed 2828

I would like to split a string on either %\d+ or \n. I was able to successfully split on either one of these two, but not on both:

> msg = 'foo %1 bar \n baz %2'

> msg.split(/(%\d+)/)
["foo ", "%1", " bar 
 baz ", "%2", ""]

> msg.split(/(\n)/)
["foo %1 bar ", "
", " baz %2"]

> msg.split(/(\n)|(%\d)/)
["foo ", undefined, "%1", " bar ", "
", undefined, " baz ", undefined, "%2", ""]

In the last case, why is undefined in the resulting array, and what should I be doing?

Update: I neglected to state that I need the delimiters. The result I want is:

["foo ", "%1", " bar ", "\n", " baz ", "%2"]
1 Answers
Related