This gist claimed that regexp was the most efficient technique.
Edit: However the performance benchmark provided by Job in the comments suggest that the split
technique is now faster. So I would recommend that nowadays.
But anyway, if you do go with the regexp approach, you should be aware that if there are no matches, then String::match()
returns null, and 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 simple way to deal with this is to substitute an empty array if the result is null:
var count = (string.match(/,/g) || []).length;
Or this avoids creating the empty array, but requires two lines of code:
var match = string.match(/,/g);
var count = match ? match.length : 0;