Javascript中奇怪的字符串拆分行为

时间:2012-09-16 12:56:30

标签: javascript

当我跑步时

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

我希望

["", "123", ""]

但它显示

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

为什么?有什么不对吗?

2 个答案:

答案 0 :(得分:2)

使用:

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

使用.split

时,您无需捕捉群组

答案 1 :(得分:1)

http://es5.github.com/#x15.5.4.14

如果separator是包含捕获括号的正则表达式,则每次匹配时,捕获括号的结果(包括任何未定义的结果)都会拼接到输出数组中。例如,

"A<B>bold</B>and<CODE>coded</CODE>".split(/<(\/)?([^<>]+)>/)

计算数组

["A", undefined, "B", "bold", "/", "B", "and", undefined, "CODE", "coded", "/", "CODE", ""]

所以,'{{123}}'.split(/(\{\{)|(\}\})/g, -1)返回

["",
"{{", undefined, // "{{" is matched, but "}}" isn't.
"123",
undefined, "}}", // "{{" isn't matched, but "}}" is matched. 
""]