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


I need to count the number of occurrences of a character in a string.

For example, suppose my string contains:

var mainStr = "str1,str2,str3,str4";

I want to find the count of comma , character, which is 3. And the count of individual strings after the split along comma, which is 4.

I also need to validate that each of the strings i.e str1 or str2 or str3 or str4 should not exceed, say, 15 characters.

4/9/2017 8:03:00 AM

Accepted Answer

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


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 jsperf test split comes ahead in speed, at least in Chrome, but again creating the extra array just doesn't seem sane.

9/8/2014 8:41:12 PM

There are at least four ways. The best option, which should also be the fastest -owing to the native RegEx engine -, is placed at the top. is currently down, otherwise I would provide you with performance statistics.

Update: Please, find the performance tests here, and run them yourselves, so as to contribute your performance results. The specifics of the results will be given later.


 ("this is foo bar".match(/o/g)||[]).length


"this is foo bar".split("o").length-1

split not recommended. Resource hungry. Allocates new instances of 'Array' for each match. Don't try that for a >100MB file via FileReader. You can actually easily observe the EXACT resource usage using Chrome's profiler option.


var stringsearch = "o"
   ,str = "this is foo bar";
for(var count=-1,index=-2; index != -1; count++,index=str.indexOf(stringsearch,index+1) );


searching for a single character

var stringsearch = "o"
   ,str = "this is foo bar";
for(var i=count=0; i<str.length; count+=+(stringsearch===str[i++]));



element mapping and filtering, not recommended due to its overall resource preallocation rather than using Pythonian 'generators'

var str = "this is foo bar"
str.split('').map( function(e,i){ if(e === 'o') return i;} )
//>[9, 10]
[9, 10].length

Share: I made this gist, with currently 8 methods of character-counting, so we can directly pool and share our ideas - just for fun, and perhaps some interesting benchmarks :)


Add this function to sting prototype :

String.prototype.count=function(c) { 
  var result = 0, i = 0;
  return result;


console.log("strings".count("s")); //2

A quick Google search got this (from

String.prototype.count=function(s1) { 
    return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;

Use it like this:

test = 'one,two,three,four'
commas = test.count(',') // returns 3

Simply, use the split to find out the number of occurrences of a character in a string.

mainStr.split(',').length // gives 4 which is the number of strings after splitting using delimiter comma

mainStr.split(',').length - 1 // gives 3 which is the count of comma


Here is a similar solution, but it uses Array.prototype.reduce

function countCharacters(char, string) {
  return string.split('').reduce((acc, ch) => ch === char ? acc + 1: acc, 0)

As was mentioned, String.prototype.split works much faster than String.prototype.replace.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]