Blueman
Blueman

Reputation: 63

How to count Letters inside a string?

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.

Upvotes: 5

Views: 21075

Answers (3)

Black Mamba
Black Mamba

Reputation: 15545

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

Upvotes: 1

Andurit
Andurit

Reputation: 5762

You can use regex for it:

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

console.log(letterCounter('Hello World!!!1'))

Upvotes: 3

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

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);
}

Upvotes: 8

Related Questions