![]() |
In this article, we will see different approaches to finding whether a character is a vowel or a consonant using JavaScript. We will check the condition of a character being Vowel and display the result. Approaches to find if a character is a vowel or consonant Table of Content 1. Using conditional statementsIn this method, we will use if-else conditional statements to check if the letter is a vowel or not and display the output result. Example: This example demonstrates the conditional statements for vowels and consonants.
Output Given character is a Consonent Given character is a Vowel 2. Using JavaScript array and Array .includes() methodIn this method, we will use JavaScript array of vowels and use includes method to check if given character is present in the array then it is a vowel and consonant otherwise. Example: In this example, we will check if vowels array includes the input cahracter or not.
Output Given character is a Vowel Given character is a Consonent 3. Using JavaScript regular expressionIn this method, we will create a regular expression for the vowels and test if the given input char satisfy the regex condition. Example: In this example, we will implement regex for the vowels and output the result.
Output Given character is a Vowel Given character is a Consonent 4. Using SetUsing a Set, vowels are stored efficiently for quick lookup. If the character is in the set, it’s a vowel; otherwise, it’s a consonant if it’s a letter, or neither. This ensures O(1) time complexity for the check. Example: The isVowelOrConsonant function checks if a character is a vowel, consonant, or neither using a Set for vowels and a regex for letters. It returns the appropriate classification.
Output Vowel Consonant Neither 5. Using Switch StatementIn this approach, we can utilize a switch statement to check if the character is a vowel or a consonant. We can define cases for each vowel and a default case for consonants. Example:
Output Given character is a Consonant Given character is a Vowel Using Character CodesUsing character codes to check if a character is a vowel involves converting the character to lowercase and comparing it against the specific vowel characters. This approach uses simple conditional checks to determine if the character is one of the vowels. Example:
Output Vowel Consonant |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 10 |