5

My Code:

function letterCounter(str) {
    var letters = 0;
    var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for (var i=0; i<str.length;i++) {
        if (str[i] === alphabet.split("")) {
            letters = letters + str[i];
        }
    }
    console.log(letterCounter("Hello World!!!1"));
}

I am not sure what mistake I am making and I am getting 0 letters as my answer. Thank you.

Sterling Archer
  • 20,452
  • 15
  • 77
  • 107
Blueman
  • 63
  • 1
  • 1
  • 5

3 Answers3

7

You are comparing a character to an array in your code with str[i] === alphabet.split("") which makes no sense, you need to check if the character is inside the array. Also, the console.log must not be inside the function, or it will make it be called recursively infinite number of times.

Use

function letterCounter(str) {
    var letters = 0;
    var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var ar = alphabet.split("");
    for (var i=0; i<str.length;i++) {
        if (ar.indexOf(str[i]) > -1) {
            letters = letters + 1;
        }
    }
    return letters;
}
console.log(letterCounter("Hello World!!!1"));

Another way is to use a regex:

var s = "Hello World!!!1";
var rx = /[a-z]/gi;
var m = s.match(rx);
if (m) {
  console.log(m.length);
}
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
2

You can use regex for it:

function letterCounter (x) {
  return x.replace(/[^a-zA-Z]/g, '').length;
}

console.log(letterCounter('Hello World!!!1'))
Andurit
  • 4,879
  • 8
  • 60
  • 100
1

To calculate number count of the letter e for example:

var str = "Hello hello hello hello";
var lengthOfE = str.match(/e/gi).length;
console.log(lengthOfE);

Then use this in loop to calculate each element's count

Black Mamba
  • 8,408
  • 4
  • 52
  • 84