从正则表达式生成数组

时间:2010-08-05 23:09:27

标签: javascript regex arrays

我有这个字符串:

{example1}{example2}{example3}

这是查找这些{ anything in it }的正则表达式:

/\{.*?\}/g

现在我想知道如何将它们放入数组中,以便我可以进行for in语句。

我想要一个类似array("{example1}","{example2}","{example3}");的数组?

2 个答案:

答案 0 :(得分:15)

your_array = string.match( pattern )

http://www.w3schools.com/jsref/jsref_match.asp

答案 1 :(得分:12)

var matches = '{example1}{example2}{example3}'.match(/\{.*?\}/g);
// ['{example1}', '{example2}', '{example3}']

See it here

此外,您应该使用for循环来遍历数组。 for in可能会产生副作用,例如收集更多东西来迭代原型链。您可以使用hasOwnProperty(),但for循环更容易。

为了提高性能,您还可以在将length属性包含在for条件之前对其进行缓存。