18

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

2
  • 2
    If you've got an actual Array, you'd be much better off using a simple for loop rather than a for...in, which may give you more than you bargained for: all extensions to Array's prototype will be listed, as well as the items in the array. Commented Aug 5, 2010 at 23:22
  • You shouldn't be iterating arrays with for-in. Use a C-style for loop, preferably. Commented Aug 5, 2010 at 23:25

2 Answers 2

21
your_array = string.match( pattern )

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

Sign up to request clarification or add additional context in comments.

3 Comments

Will this make an array such like array("{example1}","{example2}","{example3}"); ?
he's a beginner i think you won't help him by posting those function singatures ;)
@zolex true. I like to at least link to w3schools instead of the straight documentation, as they have examples and the "try it now" feature.
14
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.