TypeScript: Count Vowels in a String

1. Introduction

Vowels are a fundamental part of understanding and analyzing language. Counting the number of vowels in a string can be helpful in various text-processing tasks. In this post, we'll create a simple TypeScript function that counts the number of vowels in a given string.

2. Program Overview

We will define a function named countVowels that takes a string as an argument. This function will then return the number of vowels present in that string. For simplicity, we'll only consider the five primary English vowels: A, E, I, O, and U.

3. Code Program

// Function to count the number of vowels in a string
function countVowels(s: string): number {
    // Convert the string to lowercase to make our search case-insensitive
    const lowerCaseStr = s.toLowerCase();

    // Define our vowels
    const vowels = ['a', 'e', 'i', 'o', 'u'];

    // Count and return the number of vowels in the string
    return [...lowerCaseStr].filter(char => vowels.includes(char)).length;
}

// Test the function
const testStr = "Hello, World!";
console.log(`Number of vowels in "${testStr}" is:`, countVowels(testStr));

Output:

Number of vowels in "Hello, World!" is: 3

4. Step By Step Explanation

1. We start by defining our function countVowels which takes a string s as its argument.

2. To make our search case-insensitive, we convert the string to lowercase using the toLowerCase() method.

3. We define an array named vowels that contains all the vowels we want to search for.

4. To count the vowels, we spread our string into an array of characters using the spread syntax (...). We then filter this array, keeping only the characters that are in our vowels array using the filter() method combined with the includes() method.

5. The length of the resulting filtered array gives us the number of vowels in the original string, which we return.

6. Finally, we test our function with a sample string "Hello, World!" and print the result.

Comments