Javascript: how many times a character appears in a string

Is there an easy way to check how many times a character appears in a string?

+51
javascript string
May 25 '10 at 9:46 a.m.
source share
4 answers

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

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

Here it is calculated how many a is in str .

+39
May 25 '10 at 9:48 a.m.
source share

In the following example a :

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

If you want case insensitive, you need something like

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

So it captures the flag "A" and "a" ... "g" is not really needed, but you need the flag "i"

+22
May 25 '10 at 9:52 a.m.
source share

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

 var string = 'aajlkjjskdjfAlsj;gkejflksajfjskda'; document.write(string.match(/a/gi).length); 

Let me explain how this works:

string.match This is the 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 says: "Find character a." It is very simple. It also contains two flags: "g" and "i". "G" says to find ALL occurrences of the character "a". Otherwise, he will find only the first, and he will never count past number one. The second flag is "i". This makes RegEx match all cases of this character. If this flag (i) was not there, the above code will only count 4, because it will skip the capital letter "A" in the string. Due to the "i" it will match upper and lower case.

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

+7
Dec 03 '14 at 17:23
source share
 var s = "dqsskjhfds"; alert(s.length - s.replace(/a/g, "").length); // number of 'a' in the string 
+3
May 25 '10 at 9:49 a.m.
source share



All Articles