Reputation: 13
When I run
'{{123}}'.split(/(\{\{)|(\}\})/g, -1)
I expect
["", "123", ""]
But it shows
["", "{{", undefined, "123", undefined, "}}", ""]
Why?? Is there anything wrong?
Upvotes: 1
Views: 172
Reputation: 160963
Use:
'{{123}}'.split(/\{\{|\}\}/)
You don't need to catch group when using .split
Upvotes: 2
Reputation: 10470
http://es5.github.com/#x15.5.4.14
If separator is a regular expression that contains capturing parentheses, then each time separator is matched the results (including any undefined results) of the capturing parentheses are spliced into the output array. For example,
"A<B>bold</B>and<CODE>coded</CODE>".split(/<(\/)?([^<>]+)>/)
evaluates to the array
["A", undefined, "B", "bold", "/", "B", "and", undefined, "CODE", "coded", "/", "CODE", ""]
So, '{{123}}'.split(/(\{\{)|(\}\})/g, -1)
returns
["",
"{{", undefined, // "{{" is matched, but "}}" isn't.
"123",
undefined, "}}", // "{{" isn't matched, but "}}" is matched.
""]
Upvotes: 1