Advertisement
Advertisement


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


Question

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.

2017/04/09
1
549
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

jsfiddle

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.

2014/09/08
795
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. jsperf.com 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.

1.

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

2.

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

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.

3.

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

4.

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++]));
 //>count:2

Update:

5.

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;} )
             .filter(Boolean)
//>[9, 10]
[9, 10].length
//>2

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 :)

https://gist.github.com/2757250

2020/06/20

Add this function to sting prototype :

String.prototype.count=function(c) { 
  var result = 0, i = 0;
  for(i;i<this.length;i++)if(this[i]==c)result++;
  return result;
};

usage:

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

A quick Google search got this (from http://www.codecodex.com/wiki/index.php?title=Count_the_number_of_occurrences_of_a_specific_character_in_a_string#JavaScript)

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
2009/05/19

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

2018/07/13

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.

2020/01/25

Source: https://stackoverflow.com/questions/881085
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]