I need to count the number of occurrences of a character in a string.
For example, suppose my string contains:
var mainStr = \"str1,str2,str3,str4\";
I made a slight improvement on the accepted answer, it allows to check with case-sensitive/case-insensitive matching, and is a method attached to the string object:
String.prototype.count = function(lit, cis) {
var m = this.toString().match(new RegExp(lit, ((cis) ? "gi" : "g")));
return (m != null) ? m.length : 0;
}
lit
is the string to search for ( such as 'ex' ), and cis is case-insensitivity, defaulted to false, it will allow for choice of case insensitive matches.
'I love StackOverflow.com'
for the lower-case letter 'o'
, you would use:
var amount_of_os = 'I love StackOverflow.com'.count('o');
amount_of_os
would be equal to 2
.
var amount_of_os = 'I love StackOverflow.com'.count('o', true);
This time, amount_of_os
would be equal to 3
, since the capital O
from the string gets included in the search.