Validating alternating vowels and consonants in JavaScript


Problem

We are required to write a JavaScript function that takes in a string of English alphabets, str, as the first and the only argument. Our function should return true if and only if the vowels and consonants appear alternatingly in the input string, false otherwise.

For example, if the input to the function is −

Input

const str = 'amazon';

Output

const output = true;

Output Explanation

Because the vowels and consonants appear alternatingly in the string ‘amazon’.

Example

Following is the code −

 Live Demo

const str = 'amazon';
const appearAlternatingly = (str = '') => {
   return str.split('').every((v,i)=>{
      if (/[aeiou]/.test(str[0])){
         if (i%2===0&&/[aeiou]/.test(v)){
            return true
         } else if (i%2!==0&&!/[aeiou]/.test(v)){
            return true
         } else {
            return false
         }
      }
      if (!/[aeiou]/.test(str[0])){
         if (i%2==0&&!/[aeiou]/.test(v)){
            return true
         } else if (i%2!==0&&/[aeiou]/.test(v)){
            return true
         } else {
            return false
         }
      }
   })
};
console.log(appearAlternatingly(str));

Output

true

Updated on: 22-Apr-2021

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements