EASY WAY TO PRINT VOWELS IN TYPESCRIPT

Introduction

In this tutorial, we’ll create a basic TypeScript program that identifies and prints vowels from a given string. TypeScript, a strongly-typed superset of JavaScript, provides robust tools for type safety and code clarity. By the end of this guide, you’ll understand how to manipulate strings and arrays in TypeScript to extract specific characters, in this case, vowels.

Code Explanation

Below is a simple TypeScript program that prints all vowels from a given string. We’ll break down each step of the program to explain how it works.

TYPESCRIPT CODE

// Function to print vowels from a given string
function printVowels(input: string): void {
    // Define a string containing all vowels
    const vowels: string = 'aeiouAEIOU';
    
    // Initialize an empty string to store found vowels
    let result: string = '';
    
    // Iterate through each character in the input string
    for (let char of input) {
        // Check if the character is a vowel
        if (vowels.includes(char)) {
            // Add the vowel to the result string
            result += char;
        }
    }
    
    // Print the result string containing only vowels
    console.log('Vowels in the string:', result);
}

// Example usage
const exampleString: string = 'Hello, TypeScript World!';
printVowels(exampleString);
TypeScript

Explanation of Each Step

Define the Function:

function printVowels(input: string): void {
TypeScript

Initialize Vowels String:

const vowels: string = 'aeiouAEIOU';
TypeScript

Initialize Result String:

let result: string = '';
TypeScript

Iterate Through the Input String:

for (let char of input) {
TypeScript

Check for Vowel:

if (vowels.includes(char)) {
TypeScript

Append Vowel to Result:

result += char;
TypeScript

Print the Result:

console.log('Vowels in the string:', result);
TypeScript

Example Usage:

const exampleString: string = 'Hello, TypeScript World!';
printVowels(exampleString);
TypeScript

Output

When you run the above TypeScript code with the example string 'Hello, TypeScript World!', the output will be:

Vowels in the string: eooieio
TypeScript

Conclusion

In this guide, we wrote a simple TypeScript program to print vowels from a string. We explored how to define functions, work with strings, and use basic control structures like loops and conditionals. This example showcases the fundamental aspects of TypeScript while providing a clear and practical application. With this knowledge, you can now experiment with other string manipulations and continue to enhance your TypeScript skills.

For further learning, you can explore the official TypeScript documentation to deepen your understanding of TypeScript’s capabilities.

Leave a Reply

Your email address will not be published. Required fields are marked *

Resize text
Scroll to Top