104

Is there a simple way to check how many times a character appears in a String?

simhumileco
  • 27,137
  • 16
  • 123
  • 105
Ruth
  • 5,258
  • 10
  • 36
  • 45
  • 4
    possible duplicate of [Count the number of occurances of a character in a string in Javascript](http://stackoverflow.com/questions/881085/count-the-number-of-occurances-of-a-character-in-a-string-in-javascript) – Michael Mrozek Oct 13 '10 at 05:30
  • Possible duplicate of [Count the number of occurrences of a character in a string in Javascript](https://stackoverflow.com/questions/881085/count-the-number-of-occurrences-of-a-character-in-a-string-in-javascript) – opyate Jul 27 '18 at 13:15

6 Answers6

90

You could remove any other character in the string and check the length:

str.replace(/[^a]/g, "").length

Here it is counted how many as are in str. The RegExp is described below:

[ // Start Character Group
^ // Not operator in character group
a // The character "a"
] // End character group
Saiansh Singh
  • 396
  • 4
  • 13
Gumbo
  • 620,600
  • 104
  • 758
  • 828
53

This counts a in below example:

str = "A man is as good as his word";
alert(str.split('a').length-1);

If you want case insensitive you'd want something like

alert(str.split( new RegExp( "a", "gi" ) ).length-1);

So that it grabs "A" and "a" ... "g" flag isn't really needed, but you do need the "i" flag

Sarfraz
  • 367,681
  • 72
  • 526
  • 573
  • 1
    @Josh It depends on what everyone likes. For instance I like this answer because it is easy to read. But someone else will prefer another answer for it's more technical, or challenging, another person will prefer another answer because it is eating less cpu and so on.. that is why JavaScript is so nice, a taste of freedom. – vdegenne Apr 11 '19 at 17:41
24

Use a RegEx to count the number of "a"s in a string.

var string = 'aajlkjjskdjfAlsj;gkejflksajfjskda';

document.write(string.match(/a/gi).length);

Let me explain how this works:

string.match This is a RegEx method. It searches for the specified RegEx inside the specified string (in this case, the string "string").

(/a/gi) This is the actual RegEx. It reads, "find the character a." It's very simple. It also carries two flags, the "g" and the "i". The "g" says to find ALL occurences of the character "a". Otherwise it would only find the first one, and it would never count past the number one. The second flag is "i". It makes the RegEx match all cases of that character. If that flag (i) was not there, the code above would only count 4, because it would skip the uppercase "A" in the string. Because of the "i", it will match upper and lower case. Remove the "i" if you you want to match letter case.

string.match returns an array of all of the matches, so we use the length method to retrieve the number of array entries. Simple as that!

Drazzah
  • 7,371
  • 7
  • 31
  • 57
  • 1
    I think you should remove the i from gi, it's a source of errors. You can add it as a bonus, but in my case I was looking specifically for case sensitive match. – Gismo Ranas Mar 14 '18 at 10:56
  • 2
    the problem here is that if you don't have "`a`" in `string`, then `string.match(/a/gi)` equals `null` and you got error `Cannot read property 'length' of null`. – pbialy May 13 '19 at 14:26
  • 1
    The 'gi' part was very helpful, Sir @Drazzah – King Friday Jan 16 '20 at 15:03
  • not gonna tag them because the comment is over 2 years old but if anyone is concerned about the problem pbialy mentioned, just put `if (string.match(/a/gi))` and that should fix the problem – Raphael Morgan Aug 11 '21 at 01:50
24

In my opinion it is more convenient and safe to avoid regular expressions in this case

It's because if we want to be able to count any kind of characters then we need to consider two expressions. One for common characters and second for special characters for example like [, ], ^ and so on. It's easy to forget about it, but even if we remember it, I think we're unnecessarily expanding our code.

In this case for string str and character ch works each of these solutions:

let count = str.split(ch).length - 1

(thanks to @Sarfraz)

or

let count = str.split('').filter(x => x == ch).length

or

let count = 0
str.split('').forEach(x => x == ch ? count++ : null)

Enjoy!

simhumileco
  • 27,137
  • 16
  • 123
  • 105
4
var s = "dqsskjhfds";
alert(s.length - s.replace(/a/g, "").length); // number of 'a' in the string
Darin Dimitrov
  • 994,864
  • 265
  • 3,241
  • 2,902
1
var a = "acvbasbb";
var b= {};
for (let i=0;i<a.length;i++){
    if((a.match(new RegExp(a[i], "g"))).length > 1){
        b[a[i]]=(a.match(new RegExp(a[i], "g"))).length;
    }
}
console.log(b);
Nitin .
  • 754
  • 7
  • 11
  • 1
    Although your code snippet might solve the issue, you should describe what’s the purpose of your code (how it solves the problem). Furthermore, you might want to check https://stackoverflow.com/help/how-to-answer – Ahmad F Mar 26 '18 at 09:44
  • @AhmadF you can use this for > How many times a character occurs in a string. and when you run this script you ll get an object with properties (characters) which occurs more then once. – Nitin . Mar 26 '18 at 10:56