Home > database >  For loop to count the number of vowels in a string (javascript)
For loop to count the number of vowels in a string (javascript)

Time:01-23

I'm writing a function that will count the number of vowels in a string. I decided to use a for-loop and an if-statement to do this.

function vowels (string) {
    var counter = 0;
    for (let i=0; i < string.length; i  ) {
        if (i == 'a' || i == 'e' || i == 'i' || i == 'o' || i == 'u') {
            counter  ;
        }return counter;
    } 
}

This is my code. When I call the function, it only returns 0 no matter how many vowels my string has. What's wrong?

CodePudding user response:

Couple of things.

  1. You're not looping through the string but the length of it. You need to use the length to get the position of the string.
  2. You're returning the counter, exiting the function, on index 0.

I also added a toLowerCase to account for casing. A === a but that depends on your use case.

Always use === operator when validating types. You can learn more here but basically == compares value only and === compares value and type.

e.g. 0 == '0' equals true and 0 === '0' equals false

function vowels (value) {
    let counter = 0;
    let char = '';
    for (let i = 0; i < value.length; i  ) {
        char = value[i].toLowerCase();
        if (char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u') {
            counter  
        }
        
    } 
    return counter;
}

vowels("AaBbCcDdEe");

returns 4. AaEe.

CodePudding user response:

function countVowels(str) {
    var count = (str.match(/[aeiou]/gi) || []).length;
    return count;
}

Check this out. You don't need a loop and all.

  • Related