This method claimed that regexp is the most efficient method.
Edit: However, the performance metric provided by Job in the comments show that the split method is faster. Therefore, I would recommend it these days.
But in any case, if you go to the regexp approach, you should know that if there are no matches, then String::match() returns null, not an empty array, as you might expect:
> 'foo'.match(/o/g) [ 'o', 'o' ] > 'foo'.match(/o/g).length 2 > 'foo'.match(/x/g) null > 'foo'.match(/x/g).length TypeError: Cannot read property 'length' of null
One easy way to handle this is to replace an empty array if the result is null:
var count = (string.match(/,/g) || []).length;
Or this avoids creating an empty array, but requires two lines of code:
var match = string.match(/,/g); var count = match ? match.length : 0;
source share