1

When I run

'{{123}}'.split(/(\{\{)|(\}\})/g, -1)

I expect

["", "123", ""]

But it shows

["", "{{", undefined, "123", undefined, "}}", ""]

Why?? Is there anything wrong?

1
  • Why have you passed a negative limit? Commented Sep 16, 2012 at 12:59

2 Answers 2

2

Use:

'{{123}}'.split(/\{\{|\}\}/)

You don't need to catch group when using .split

Sign up to request clarification or add additional context in comments.

1 Comment

You don't need the global flag, and -1 as a limit is not very useful either I think.
1

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. 
""]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.