srgg6701
srgg6701

Reputation: 2048

JS RegExp matched entries count

Is it possible to get a count of entries that matched of RegExp in JS? Let's assume an simpliest example:

var pattern =/\bstring\b/g;
var str = "My the best string comes here. Do you want another one? That will be a string too!";

So how to get its count? If I try use a standard method exec():

pattern.exec(str);

...it shows me an array, contains unique matched entry:

["string"]

there is the lenght 1 of this array, but in reality there are 2 points where matched entry was found.

Upvotes: 1

Views: 137

Answers (1)

Greenhorn
Greenhorn

Reputation: 1700

You can achieve using .match() :

var pattern =/\bstring\b/g;
var str = "My the best string comes here. Do you want another one? That will be a string too!";
alert(str.match(pattern).length);

Demo Fiddle

Upvotes: 1

Related Questions