Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 310
Blueman Avatar asked Sep 12 '16 13:09

Blueman


1 Answers

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);
}
like image 66
Wiktor Stribiżew Avatar answered Sep 28 '22 15:09

Wiktor Stribiżew