views:

224

answers:

4

Hi all

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

Thanks in Advance Ruth

+7  A: 

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.

Gumbo
Thank you very much
Ruth
+3  A: 
var s = "dqsskjhfds";
alert(s.length - s.replace(/a/g, "").length); // number of 'a' in the string
Darin Dimitrov
How convoluted.
Kobi
+12  A: 

Match the character with a regular expression, make it global, count the number of matches.

"aabbaa".match(/a/g).length;
David Dorward
would be better then the replace as mentioned below.
Lalit
Thats good to know thank you
Ruth
+1  A: 

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