views:

46

answers:

2

In Javascript, how can I use a regular expression to iterate through a string to isolate all occurances of strings starting with a '{' and ending with a '}' character?

So, for example the haystack string may be:

Lorem ipsum dolor {sit} amet, consectetur adipiscing elit. {Praesent} tincidunt, sapien non ultricies posuere, justo felis {placerat erat}, a laoreet felis justo in nisl. Donec.

The function would therefore need to return the following values:

  1. sit
  2. Praesent
  3. placerat erat

All help appreciated!

+4  A: 
string.match(/{.*?}/g);

To elaborate: we use the match method for Strings to execute a regexp search. The g at the end of the regexp stand for 'global' and means find all matches. When executed in g mode the match method returns an array of all matches.

As for the regexp itself, its rather simple. Just find zero or more (*) instances of any character (.) between { and }.

slebetman
Many thanks for the incredibly quick reply, works like a charm!
Ergo Summary
Since `{` and `}` are special characters in regular expressions, they should always be escaped (`\{` and `\}`). In this case, the context makes their intended meaning clear, but this may not always be the case. Plus, some regex engine may treat this as a Syntax Error.
Tim Pietzcker
+5  A: 

You can do it like this:

var subject = 'Lorem ipsum dolor {sit} amet, consectetur adipiscing elit. {Praesent} tincidunt, sapien non ultricies posuere, justo felis {placerat erat}, a laoreet felis justo in nisl. Donec.'
subject.match(/\{[^}]+\}/g);

Note that it still contains the { and }.

WoLpH
Many thanks for the reply, much appreciated indeed!
Ergo Summary