Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you count occurrences of each character in a string in JavaScript?

To count the number of occurrences for each char in a JavaScript string, we can create an object that keeps track of how many characters are in each string. Then we can loop through each character of the string with a for-of loop. to count the number of occurrences in each character in str with the countChar function.

How do you find the number of occurrences of a character in a string?

Use the count() Function to Count the Number of a Characters Occuring in a String in Python. We can count the occurrence of a value in strings using the count() function. It will return how many times the value appears in the given string.

How do you count a string occurrence in a string?

First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.

How do you count occurrences in JavaScript?

In JavaScript, we can count the string occurrence in a string by counting the number of times the string present in the string. JavaScript provides a function match(), which is used to generate all the occurrences of a string in an array.


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


There are at least five ways. The best option, which should also be the fastest (owing to the native RegEx engine) is placed at the top.

Method 1

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

Method 2

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

Split not recommended as it is resource hungry. It allocates new instances of 'Array' for each match. Don't try it for a >100MB file via FileReader. You can observe the exact resource usage using Chrome's profiler option.

Method 3

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

Method 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++]));
     // returns 2

Method 5

Element mapping and filtering. This is 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
    // returns 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 :)


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

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


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

You can also rest your string and work with it like an array of elements using

  • Array.prototype.filter()

const mainStr = 'str1,str2,str3,str4';
const commas = [...mainStr].filter(l => l === ',').length;

console.log(commas);

Or

  • Array.prototype.reduce()

const mainStr = 'str1,str2,str3,str4';
const commas = [...mainStr].reduce((a, c) => c === ',' ? ++a : a, 0);

console.log(commas);

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.