Here are four ways to do it... (well, 3.something)
var myString:String = "The quick brown fox jumped over the lazy "
+ "dog. The quick brown fox jumped over the lazy dog.";
var numOfD:int = 0;
// 1# with an array.filter
numOfD = myString.split("").filter(
function(s:String, i:int, a:Array):Boolean {
return s.toLowerCase() == "d"
}
).length;
trace("1# counts ", numOfD); // output 1# counts 4
// 2# with regex match
numOfD = myString.match(/d/gmi).length;
trace("2# counts ", numOfD); // output 2# counts 4
// 3# with for loop
numOfD = 0;
for (var i:int = 0; i < myString.length; )
numOfD += (myString.charAt(++i).toLocaleLowerCase() == "d");
trace("3# counts ", numOfD); // output 3# counts 4
// 4# with a new prototype function (and regex)
String['prototype'].countOf =
function(char:String):int {
return this.match(new RegExp(char, "gmi")).length;
};
// -- compiler 'strict mode' = true
numOfD = myString['countOf']("d");
trace("4# counts ", numOfD); // output 4# counts 4
// -- compiler 'strict mode' = false
numOfD = myString.countOf("d");
trace("4# counts ", numOfD); // output 4# counts 4