user1087726
user1087726

Reputation: 13

Strange string split behavior in Javascript

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

Answers (2)

xdazz
xdazz

Reputation: 160833

Use:

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

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

Upvotes: 2

clyfish
clyfish

Reputation: 10450

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

Related Questions