简体   繁体   中英

Javascript: how to check if letter "Y" is vowel or consonant?

Is the letter Y a vowel or a consonant? Traditionally, AEIO 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?

PS 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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM