Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVASCRIPT: Count the number of REGEX results

This is what regex should find { anything in it }, and then I want to count the number of results what the regex found.

So I have a string like this:

{example1}{example2}{example3} in this case the count number is 3

like image 932
Adam Halasz Avatar asked Dec 23 '22 00:12

Adam Halasz


1 Answers

you need the global regex flag (g) to match all occurrences and then simply get the length of the result. the ? makes the .* ungreedy, otherwise it would only once fit the first and the last bracket as regexps are greedy by default.

var source = "{example1}{example2}{example3}";
var count = source.match(/\{.*?\}/g).length;
like image 79
Andreas Linden Avatar answered Jan 09 '23 15:01

Andreas Linden