When I run
'{{123}}'.split(/(\{\{)|(\}\})/g, -1)
I expect
["", "123", ""]
But it shows
["", "{{", undefined, "123", undefined, "}}", ""]
Why?? Is there anything wrong?
-
Why have you passed a negative limit?David Thomas– David Thomas2012年09月16日 12:59:26 +00:00Commented Sep 16, 2012 at 12:59
2 Answers 2
Use:
'{{123}}'.split(/\{\{|\}\}/)
You don't need to catch group when using .split
answered Sep 16, 2012 at 12:58
xdazz
161k38 gold badges255 silver badges278 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
pimvdb
You don't need the global flag, and
-1 as a limit is not very useful either I think.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.
""]
answered Sep 16, 2012 at 13:14
clyfish
10.5k2 gold badges33 silver badges23 bronze badges
Comments
lang-js