Write a function called countVowels
that takes in a string and returns the number of vowels in the string.
/**
* Returns the number of vowels in a string.
* @param {string} str - The string to search.
* @returns {number} - The number of vowels in the string.
*/
function countVowels(str: string): number;
countVowels('hello'); // 2
countVowels('why'); // 0
countVowels('mississippi'); // 4
- It shouldn't matter if the input string is uppercase or lowercase
Click For Solution
function countVowels(str) {
const formattedStr = str.toLowerCase();
let count = 0;
for (let i = 0; i < formattedStr.length; i++) {
const char = formattedStr[i];
if (
char === 'a' ||
char === 'e' ||
char === 'i' ||
char === 'o' ||
char === 'u'
) {
count++;
}
}
return count;
}
- Make the string lowercase. This is because we want to count both uppercase and lowercase vowels.
- Create a variable called
count
and set it to0
. This is the variable we will use to keep track of how many vowels we have found. - Create a
for
loop that will loop through each character in the string. We then create a variable calledchar
and set it to the current character in the string. - Check if the character is a vowel. If it is, we increment
count
by1
. Once we have looped through the entire string, we returncount
.
test('Counting vowels in a string', () => {
expect(countVowels('Hello, World!')).toBe(3);
expect(countVowels('JavaScript')).toBe(3);
expect(countVowels('OpenAI Chatbot')).toBe(6);
expect(countVowels('Coding Challenge')).toBe(5);
});