Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Validating alternating vowels and consonants in JavaScript
Validating alternating vowels and consonants is a common string pattern validation problem. We need to check if vowels (a, e, i, o, u) and consonants alternate throughout the string.
Problem Statement
Write a JavaScript function that takes a string of English alphabets and returns true if vowels and consonants appear alternatingly, false otherwise.
For example:
Input: 'amazon'
Output: true
Explanation: a(vowel) ? m(consonant) ? a(vowel) ? z(consonant) ? o(vowel) ? n(consonant)
Solution
const str = 'amazon';
const appearAlternatingly = (str = '') => {
if (str.length === 0) return true;
return str.split('').every((char, index) => {
const isVowel = /[aeiou]/i.test(char);
const firstIsVowel = /[aeiou]/i.test(str[0]);
if (firstIsVowel) {
// If string starts with vowel: even indices should be vowels, odd should be consonants
return (index % 2 === 0) ? isVowel : !isVowel;
} else {
// If string starts with consonant: even indices should be consonants, odd should be vowels
return (index % 2 === 0) ? !isVowel : isVowel;
}
});
};
console.log(appearAlternatingly(str));
console.log(appearAlternatingly('hello')); // false - two consonants together
console.log(appearAlternatingly('unite')); // true - u,n,i,t,e alternates
true false true
How It Works
The function uses the every() method to check each character:
- Determines if the first character is a vowel or consonant
- For each character, checks if it follows the alternating pattern based on its index
- Uses modulo operator (%) to identify even/odd positions
- Returns
trueonly if all characters follow the pattern
Alternative Approach
const validateAlternating = (str) => {
const isVowel = (char) => 'aeiouAEIOU'.includes(char);
for (let i = 1; i < str.length; i++) {
const currentIsVowel = isVowel(str[i]);
const previousIsVowel = isVowel(str[i - 1]);
// Adjacent characters should have different types
if (currentIsVowel === previousIsVowel) {
return false;
}
}
return true;
};
console.log(validateAlternating('amazon')); // true
console.log(validateAlternating('aeiou')); // false - all vowels
console.log(validateAlternating('bcdfg')); // false - all consonants
true false false
Comparison
| Method | Time Complexity | Readability | Performance |
|---|---|---|---|
| Using every() | O(n) | Good | Slower (creates array) |
| Using for loop | O(n) | Better | Faster (early termination) |
Conclusion
Both approaches effectively validate alternating vowel-consonant patterns. The loop method offers better performance with early termination, while the every() method provides functional programming style.
