Home > Software engineering >  Javascript: how to check if letter "Y" is vowel or consonant?
Javascript: how to check if letter "Y" is vowel or consonant?

Time:09-03

Is the letter Y a vowel or a consonant? Traditionally, A E I O and U are vowels and the rest of the letters are consonants. However, sometimes the letter Y represents a vowel sound AND sometimes a consonant sound.

How to check if letter "Y" is vowel or consonant in JavaScript?

P.S. For example, I have a word "play" (Y is vowel), or I have a word "year" (Y is consonant). How to check in any word that has "Y" - do "Y" is vowel or consonant?

P.P.S. How to make check using next rules: https://www.woodwardenglish.com/letter-y-vowel-or-consonant/

CodePudding user response:

More likely using the rules in the link you provide as test conditions. Is 'easier' to test the two conditions to be consonant:

  1. 'Y' should be at start of the word
  2. 'Y' should be at the start of the syllabe
// ! Y as a consonant

const vowelRegex = new RegExp(/[aeiou]/gi);

const words = [ 'lawyer', 'beyond', 'annoy', 'tyrant', 'dynamite', 'typical', 'pyramid', 'yes', 'young' ]

const vowelOrConsonant = ( word ) => {
  const isAtStart = word[0] === 'y';
  if( isAtStart ){
    console.log( `${word} Y is consonant.` );
    return;
  }
  // has a letter after the 'y'
  const nextLetter = word[ word.indexOf('y')   1 ] ?? false;
  if( nextLetter && nextLetter.match(vowelRegex) ){
    console.log( `${word} Y is consonant.` );
    return;
  }
  console.log( `${word} Y is vowel.` );
}

words.forEach( word => {
  vowelOrConsonant(word);
})

To make this more accurate you migth need to divide the word into syllabes while adding headaches.

  • Related