1

当我跑

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

我预计

["", "123", ""]

但它显示

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

为什么??有什么不对的吗?

4

2 回答 2

2

采用:

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

使用时不需要抓组.split

于 2012-09-16T12:58:26.147 回答
1

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

如果 separator 是一个包含捕获括号的正则表达式,那么每次 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. 
""]
于 2012-09-16T13:14:47.100 回答