javascript 从正则表达式制作数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3419882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:07:13  来源:igfitidea点击:

Make array from regex

javascriptregexarrays

提问by Adam

I have this string:

我有这个字符串:

{example1}{example2}{example3}

This is the regular expression to find these {anything in it}:

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

/\{.*?\}/g

Now I want to know how put them in an array so I can do a for instatement.

现在我想知道如何将它们放在一个数组中,以便我可以做一个for in声明。

I want an array something like array("{example1}","{example2}","{example3}");?

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

回答by alex

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

See it here.

在这里看到它

Also, you should probably use a forloop to iterate through the array. for incan have side effects, such as collecting more things to iterate through the prototype chain. You can use hasOwnProperty(), but a forloop is just that much easier.

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

For performance, you can also cache the lengthproperty prior to including it in the forcondition.

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