Can anyone tell me how can I check this by Regex form validation in javascript.
Student Name must contain only alphabets. There must be equal number of Vowels and Consonants.
Can anyone tell me how can I check this by Regex form validation in javascript.
Student Name must contain only alphabets. There must be equal number of Vowels and Consonants.
On
You will need to create a function that does two things:
You will need the following expresisons:
/^[a-z]+$/i – Only alpha characters (case-insensitive)/[aeiouy]/ig – Only vowels/[^aeiouy]/ig– Only consonantsconst isValidName = (name) =>
/^[a-z]+$/i.test(name) &&
name.match(/[aeiouy]/ig).length === name.match(/[^aeiouy]/ig).length;
console.log(isValidName('Gene')); // Valid
console.log(isValidName('Abby')); // Valid
console.log(isValidName('Charles')); // Invalid
On
The following code can be used to validate:
const validateStudentName = (name) => {
const regExp = /[^a-zA-Z]/;
const isEven = name.length % 2 == 0;
const vowels = ['a', 'e', 'i', 'o', 'u'];
const vowelCount = [...name].reduce((sum, char) => vowels.includes(char.toLowerCase()) ? sum + 1 : sum, 0);
console.log(!regExp.test(name) && isEven && vowelCount === name.length / 2);
}
validateStudentName("abaci");
I don't think you can do it using Regex only.
My solution replaces all characters from a string that are not a vowel and returns it's length, same for consonants. Then all you have to do is check if the number of consonants matches the vowels.