libsfan01 said the following on 8/12/2006 1:34 PM:
hi all
how do u get js to work out the number of times a given char occurs in
a given string?
You count them. Seriously, there is no built in "howManyTimesItOccurs"
type function. You will have to write your own. You also have to decide
whether "M" and "m" are the same or not.
Simple start, there are other ways also that use charAt:
var origString = "My mama told me";
var characterToCount = "m";
var counter = 0;
//if you don't want "M" and "m" to count the same
//remove the .toLowerCase() from the line below
var myArray = origString.toLowerCase().split('');
for (i=0;i<myArray.length;i++)
{
if (myArray
== characterToCount)
{
counter++;
}
}
alert('The character ' + characterToCount + ' appears ' +
counter + ' times in the sequence:\n' + origString)