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...

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');
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.