JavaScript Program to Find if a Character is a Vowel or Consonant
Last Updated :
20 Sep, 2023
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
- Using conditional Statements
- Using JavaScript array and .include method
- Using Regular expression
In 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.
Javascript
function checkChar(char){
ch = char.toLowerCase();
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' )
return console.log( "Given character is a Vowel" );
return console.log( "Given character is a Consonent" );
}
checkChar( 'G' );
checkChar( 'A' )
|
Output
Given character is a Consonent
Given character is a Vowel
In 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.
Javascript
function checkChar(char){
ch = char.toLowerCase();
const arr = [ 'a' , 'e' , 'i' , 'o' , 'u' ]
if (arr.includes(ch))
return console.log( "Given character is a Vowel" );
return console.log( "Given character is a Consonent" );
}
checkChar( 'E' );
checkChar( 'J' );
|
Output
Given character is a Vowel
Given character is a Consonent
In 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.
Javascript
function checkChar(char){
ch = char.toLowerCase();
const regex = /^[aeiou]$/i;
if (regex.test(ch))
return console.log( "Given character is a Vowel" );
return console.log( "Given character is a Consonent" );
}
checkChar( 'I' );
checkChar( 'Z' );
|
Output
Given character is a Vowel
Given character is a Consonent
Share your thoughts in the comments
Please Login to comment...