Hi all
Is there a simple way to chack how many times a character appears in a String?
Thanks in Advance Ruth
Hi all
Is there a simple way to chack how many times a character appears in a String?
Thanks in Advance Ruth
You could remove any other character in the string and check the length:
str.replace(/[^a]/g, "").length
Here it is counted how many a
s are in str
.
var s = "dqsskjhfds";
alert(s.length - s.replace(/a/g, "").length); // number of 'a' in the string
Match the character with a regular expression, make it global, count the number of matches.
"aabbaa".match(/a/g).length;
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