Count Vowels
Write a TypeScript function that counts the number of vowel characters (a, e, i, o, u) in a given string. The count should be case-insensitive, so both uppercase and lowercase vowels count.
Define an array or string of vowel characters. Loop through the input string, checking each character. Convert to lowercase before comparing to make it case-insensitive. Use a for loop with index and charAt() for string access.
Edge cases include empty strings (return 0), strings with no vowels (return 0), and mixed case input. The function returns an integer count.
Counting vowels is a fundamental string processing task. The indexOf() method checks if a character exists in a string. Converting to lowercase ensures case-insensitive comparison. TypeScript's type annotations for string parameters and number return values provide clear documentation of the function signature.
TypeScript adds static type checking to JavaScript, catching errors at compile time rather than runtime. The function signature `function countVowels(text: string): number` declares the parameter type and return type, enabling the TypeScript compiler to verify correct usage.
The charAt() method is used instead of bracket notation (text[i]) because TypeScript's type system prefers charAt() for string access in certain compilation targets. The indexOf() method returns -1 when a substring is not found, so checking for !== -1 is the standard pattern.
Example Input & Output
Algorithm Flow

Solution Approach
Define a string containing all vowels: 'aeiou'. Initialize count = 0. Loop through each character of the input string using a for loop. Access characters with charAt(i). Convert each character to lowercase and check if it exists in the vowel string using indexOf(). Increment count if found.
The time complexity is O(n). Space complexity is O(1).
Best Answers
function countVowels(text: string): number {
var count = 0;
var vowels = "aeiou";
for (var i = 0; i < text.length; i++) {
if (vowels.indexOf(text.charAt(i).toLowerCase()) !== -1) count++;
}
return count;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
