We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,619 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
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...

2
Contributors
1
Reply
6 Hours
Discussion Span
3 Months Ago
Last Updated
4
Views
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

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0555 seconds using 2.67MB