Count the vowels
TypeScript
Easy
Objective
Write a function that counts & returns the number of vowels in a string
Requirements
The function should be called
countVowels
It should take a single string as an argument
Your solution should be implemented in TypeScript
Check your solution
Tests
Function name is countVowels | |||
countVowels("hello world") | Expected: | 3 | |
countVowels("Lorem Ipsum Dolor Sit Amet") | Expected: | 9 | |
countVowels("The quick brown fox jumps over the lazy dog.") | Expected: | 11 |
Solution
Here's how I would approach this, but keep in mind there might be other ways to solve this problem.
function countVowels (string: string): number {
// Convert string to lower case
const stringInLowerCase = string.toLowerCase();
const vowels = ['a', 'e', 'i', 'o', 'u'];
let count = 0;
// Loop through the string
for(let i = 0; i < stringInLowerCase.length; i++) {
// Check if the current character is a vowel
if (vowels.includes(stringInLowerCase[i])) {
// If it is, increment the count
count++;
}
}
return count;
}
Click to reveal