Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make array from regex

I have this string:

{example1}{example2}{example3}

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

/\{.*?\}/g

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

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

like image 485
Adam Halasz Avatar asked Aug 05 '10 23:08

Adam Halasz


2 Answers

your_array = string.match( pattern )

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

like image 55
hookedonwinter Avatar answered Nov 14 '22 21:11

hookedonwinter


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

See it here.

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

For performance, you can also cache the length property prior to including it in the for condition.

like image 13
alex Avatar answered Nov 14 '22 23:11

alex