JavaScript - Find if a Character is a Vowel or Consonant
Last Updated :
02 Dec, 2024
Here are the different methods to find if a character is a vowel or consonant
1. Using Conditional Statements (If-Else)
The most widely used approach is to check the character against vowels (both uppercase and lowercase) using conditional statements (if-else). This method is simple and effective for small scripts or quick tasks.
JavaScript
let s = 'a';
if (s === 'a' || s === 'e' || s === 'i' || s === 'o' || s === 'u' ||
s === 'A' || s === 'E' || s === 'I' || s === 'O' || s === 'U') {
console.log(`${s} is a vowel`);
} else {
console.log(`${s} is a consonant`);
}
- The if-else statement checks if the character is one of the vowels (both lowercase and uppercase).
- This method is simple and highly readable, but as the number of conditions increases, it can become less efficient and harder to maintain.
2. Using JavaScript Array and Array.includes() Method
Another efficient approach is using an array of vowels and checking if the character exists within that array. The includes() method provides a clean and readable way to check membership.
JavaScript
let s = 'e';
let vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'];
if (vowels.includes(s)) {
console.log(`${s} is a vowel`);
} else {
console.log(`${s} is a consonant`);
}
- The includes() method checks if the character s exists in the vowels array.
- This method is more scalable than using multiple if conditions and is cleaner for checking membership in a predefined set of values.
3. Using JavaScript Regular Expression
Regular expressions (regex) are another powerful tool for pattern matching. You can use a regex to check if the character matches any vowel pattern.
JavaScript
let s = 'I';
let regex = /^[aeiouAEIOU]$/;
if (regex.test(s)) {
console.log(`${s} is a vowel`);
} else {
console.log(`${s} is a consonant`);
}
- The regex /^[aeiouAEIOU]$/ checks if the character is a single vowel (either uppercase or lowercase).
- test() method returns true if the character matches the regex, making it a concise and effective approach.
4. Using Set
A Set is a collection of unique values in JavaScript. Using a Set to store vowels allows for quick lookup times with the has() method, which is often faster than arrays for large sets of data.
JavaScript
let s = 'o'; // Input character
let vowels = new Set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']);
if (vowels.has(s)) {
console.log(`${s} is a vowel`);
} else {
console.log(`${s} is a consonant`);
}
- The Set data structure ensures each vowel is stored only once and can be checked efficiently with has().
- This method is useful when dealing with a larger set of vowels or other repeated characters, as the lookup time is constant, O(1).
5. Using Switch Statement
A switch statement can also be used to determine if a character is a vowel or consonant. It's an alternative to using multiple if-else conditions and can make the code look cleaner when you have a fixed set of values.
JavaScript
let s = 'U';
switch (s.toLowerCase()) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
console.log(`${s} is a vowel`);
break;
default:
console.log(`${s} is a consonant`);
}
- The switch statement compares the lowercase version of the character with the vowels.
- If it matches any of the vowel cases, it prints that the character is a vowel; otherwise, it defaults to consonant.
6. Using Character Codes
For a more advanced approach, you can use the character codes of the letters to check if the character is a vowel. Vowels have specific character codes, so you can use those ranges to determine the character type.
JavaScript
let s = "i";
let charCode = s.charCodeAt(0);
if (
(charCode >= 97 && charCode <= 101) ||
(charCode >= 105 && charCode <= 111) ||
charCode === 117 ||
charCode === 65 ||
charCode === 69 ||
charCode === 73 ||
charCode === 79 ||
charCode === 85
) {
console.log(`${s} is a vowel`);
} else {
console.log(`${s} is a consonant`);
}
- charCodeAt(0) retrieves the Unicode character code of the character.
- The character codes for vowels (a, e, i, o, u) are checked using ranges for lowercase and uppercase letters.
Which Approach to Choose?
Method | When to Use | Why Choose It |
---|
Conditional Statements (If-Else) | For small scripts or quick checks. | Simple, readable, and effective for checking small sets of values. |
Array and includes() Method | When you want a clean and scalable solution with a fixed set. | Easy to maintain and extend, works well for predefined collections. |
Regular Expression | When you need a concise and flexible solution for pattern matching. | Great for validating input against patterns, such as vowels. |
Set | When performance is a concern, and you need fast membership checking. | Faster lookups for larger sets or repetitive checks. |
Switch Statement | When you have a small, fixed set of conditions. | Cleaner syntax than if-else for multiple conditions. |
Character Codes | For performance-critical applications where character codes are known. | Efficient but more complex, suitable for low-level operations. |
For simple use cases, if-else and Array.includes() are quick and readable solutions. If you're dealing with larger data sets or require more optimized performance, consider using Set or character codes. For pattern matching and flexibility, regular expressions offer a powerful approach.
Similar Reads
JavaScript Program to Check if a Character is Vowel or Not In this article, we will check if the input character is a vowel or not using JavaScript. Vowel characters are âaâ, âeâ, âiâ, âoâ, and âuâ. All other characters are not vowels. Examples: Input : 'u'Output : TrueExplanation: 'u' is among the vowel characters family (a,e,i,o,u).Input : 'b'Output : Fal
4 min read
JavaScript - String Contains Only Alphabetic Characters or Not Here are several methods to check if a string contains only alphabetic characters in JavaScriptUsing Regular Expression (/^[A-Za-z]+$/) - Most USedThe most common approach is to use a regular expression to match only alphabetic characters (both uppercase and lowercase).JavaScriptlet s = "HelloWorld"
2 min read
JavaScript Program to Reverse Consonants in a Given String Without Affecting the Other Elements In this article, we have given a string and the task is to write a javascript program to reverse only the consonants of a string without affecting the other elementsâ positions and printing the output in the console.Examples:Input: helloOutput: lelhoExplanation: h,l,l are consonants in the given str
6 min read
JavaScript Program to Remove Vowels from a String The task is to write a JavaScript program that takes a string as input and returns the same string with all vowels removed. This means any occurrence of 'a', 'e', 'i', 'o', 'u' (both uppercase and lowercase) should be eliminated from the string. Given a string, remove the vowels from the string and
2 min read
JavaScript Program to Match Single Character with Multiple Possibilities In this article, we will write programs to check all possible matching in JavaScript. We will check the occurrence of characters individually in the given string or sequence. In this article, we will check the occurrence of vowels in the given string. Table of Content Using JavaScript RegExp test()
3 min read
PHP Program to Check Whether a Character is a Vowel or Consonant There are a total of 26 letters in the English alphabet. There are 5 vowel letters and 21 consonant letters. The 5 vowel letters are: "a", "e", "i", "o", and "u" rest are consonants. There are different approaches to checking whether a character is a vowel or a consonant. These are the different App
3 min read
PHP Program to Check if a Given Letter is Vowel or Consonant Determining whether a given letter is a vowel or consonant is a fundamental programming task that can be approached in various ways using PHP. This article explores multiple methods to achieve this, catering to beginners and experienced developers alike.Understanding Vowels and ConsonantsBefore divi
4 min read
JavaScript - How to Get a Number of Vowels in a String? Here are the various methods to get the number of vowels in a string using JavaScript.1. Using a for LoopThis is the most basic and beginner-friendly approach. It uses a loop to iterate over each character and checks if it is a vowel.JavaScriptconst cVowels = (s) => { const vowels = "aeiouAEIOU";
3 min read
Javascript Program to Check if a given string is Pangram or not In this article, we are going to implement algorithms to check whether a given string is a pangram or not. Pangram strings are those strings that contain all the English alphabets in them.Example: Input: âFive or six big jet planes zoomed quickly by tower.â Output: is a Pangram Explanation: Does'not
7 min read
PHP Program to Count Number of Vowels in a String Given a String, the task is to count the number of Vowels in a given string in PHP. Counting the number of vowels in a string is a common programming task, often encountered in text processing and data analysis. Here, we will cover three common scenarios for counting the number of Vowels in a String
3 min read