Algorithm


  1. Initialize Variables:

    • Create a variable inputString to store the input string.
    • Create a variable vowelCount and set it to 0 to keep track of the count of vowels.
  2. Input:

    • Accept the input string from the user or use a predefined string.
  3. Convert to Lowercase:

    • Convert the entire input string to lowercase to make the matching case-insensitive.
  4. Iterate Through Characters:

    • Use a loop to iterate through each character in the string.
  5. Check for Vowels:

    • For each character, check if it is a vowel (a, e, i, o, u).
    • You can use a conditional statement (if-else) or a switch statement to check for each vowel.
  6. Increment Count:

    • If the character is a vowel, increment the vowelCount variable by 1.
  7. Output Result:

    • After the loop completes, output or display the value of vowelCount as the result.

 

Code Examples

#1 Code Example- Count the Number of Vowels Using Regex

Code - Javascript Programming

// program to count the number of vowels in a string

function countVowel(str) { 

    // find the count of vowels
    const count = str.match(/[aeiou]/gi).length;

    // return number of vowels
    return count;
}

// take input
const string = prompt('Enter a string: ');

const result = countVowel(string);

console.log(result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a string: JavaScript program
5

#2 Code Example- Count the Number of Vowels Using for Loop

Code - Javascript Programming

// program to count the number of vowels in a string

// defining vowels
const vowels = ["a", "e", "i", "o", "u"]

function countVowel(str) {
    // initialize count
    let count = 0;

    // loop through string to test if each character is a vowel
    for (let letter of str.toLowerCase()) {
        if (vowels.includes(letter)) {
            count++;
        }
    }

    // return number of vowels
    return count
}

// take input
const string = prompt('Enter a string: ');

const result = countVowel(string);

console.log(result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a string: JavaScript program
5
Advertisements

Demonstration


JavaScript Programing Example to Count the Number of Vowels in a String-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way