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 followi开发者_开发技巧ng values:
- sit
- Praesent
- placerat erat
All help appreciated!
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 }
.
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 }
.
精彩评论