Adam Halasz
Adam Halasz

Reputation: 58301

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}"); ?

Upvotes: 18

Views: 24217

Answers (2)

alex
alex

Reputation: 490153

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.

Upvotes: 14

hookedonwinter
hookedonwinter

Reputation: 12666

your_array = string.match( pattern )

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

Upvotes: 21

Related Questions