Start New Discussion Reply to this Discussion Character Count in String
Problem :
String : Hello World
Output :
H occured 1 times
e occured 1 times
l occured 3 times
o occured 2 times
W occured 1 times
r occured 1 times
d occured 1 times
How to do it in Javascript...
livlikestar.jame
Newbie Poster
1 post since Feb 2013
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0
There's probally a simpler way, but this should work:
var myString = "Hello Word";
var counters = {};
// Count letters
for(var i=0, l=myString.length,c; i<l, c=myString[i]; i=i+1) {
if ( typeof counters[c] != 'undefined' ) {
counters[c] = 1;
}
else {
counters[c] = counters[c] + 1;
}
}
// Show letters
for(var c in counters) {
document.write(c + ' ocurred ' + counters[c] + ' times');
}
AleMonteiro
Master Poster
752 posts since Aug 2010
Reputation Points: 129
Solved Threads: 140
Skill Endorsements: 23
© 2013 DaniWeb® LLC
Page rendered in 0.0555 seconds
using 2.67MB