Why do string.split () results include undefined?

I would like to split the string into %\d+or \n. I was able to successfully split one of these two, but not 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 latter case, why undefinedin the resulting array, and what should I do?

Update . I forgot to indicate that I need delimiters. As a result, I want:

["foo ", "%1", " bar ", "\n", " baz ", "%2"]
+4
source share
1 answer

Quoting an MDN doc for String.prototype.split:

, , , , ( undefined) .

, - , . undefined - "", \n ( , %\d ), - %\d ( \n )... .

, ( ):

msg.split(/\n|%\d/); // ["foo ", " bar ", " baz ", ""]

, :

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

All Articles