开发者

How to use a regular expression to find delimited needles within a haystack in Javascript?

开发者 https://www.devze.com 2023-01-16 16:50 出处:网络
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?

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:

  1. sit
  2. Praesent
  3. 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 }.

0

精彩评论

暂无评论...
验证码 换一张
取 消