Count the number of occurrences of a character in a string in Javascript

I have updated this answer. I like the idea of using a match better, but it is slower:

console.log(("str1,str2,str3,str4".match(/,/g) || []).length); //logs 3

console.log(("str1,str2,str3,str4".match(new RegExp("str", "g")) || []).length); //logs 4

Expand snippet

Use a regular expression literal if you know what you are searching for beforehand, if not you can use the RegExp constructor, and pass in the g flag as an argument.

match returns null with no results thus the || []

The original answer I made in 2009 is below. It creates an array unnecessarily, but using a split is faster (as of September 2014). I’m ambivalent, if I really needed the speed there would be no question that I would use a split, but I would prefer to use match.

Old answer (from 2009):

If you’re looking for the commas:

(mainStr.split(",").length - 1) //3

If you’re looking for the str

(mainStr.split("str").length - 1) //4

Both in @Lo’s answer and in my own silly performance test split comes ahead in speed, at least in Chrome, but again creating the extra array just doesn’t seem sane.

Leave a Comment