Need some help trying to determine what character occurs most frequently in a textarea. Not sure how to do this, since I am a JS noob.
Do I really have to store every single character in an array and then sort it? Is there a Regular Expression for this?
Thanks in advance!
Aye, pretty much like that except that i need to count all possible characters and return the most frequent one. I took a look at the script you posted, but it’s a little inconvenient for my purpose, cause it’s declaring variables for every letter. Thanks though!
/*
You can use a regular expression, but you’d need to use exec,
and go over the same string again for every different character,
and still have to juggle the matches.
I’d split the string into characters and join it back sorted.
A regular expression can then match all the sets of
consecutive duplicate letters in one pass.
*/
function lettercount(s, force){
var cs= [], L,
s= ta.value.toLowerCase().split('').sort().join('');
var M= s.match(/([a-z])\\1+/g)
M.sort(function(a, b){
return a.length> b.length? -1: 1;
});
if(force) return M;
L= M[0].length;
while(M.length && M[0].length== L){
cs.push(M.shift().charAt(0));
}
return cs.join(' and ')+' occurred '+L+' times.'
}
[B]var ta={
value: 'The quick red fox jumps over the lazy brown dog\‘s back’
};
alert(lettercount(ta.value));[/B]
/* returned value: (String)
o and e occurred 4 times.
*/
If you want to avoid sorting and regexps, you can build an associative array dynamically, storing the count of each character and recording the highest as you go: