Is there a way to check if a word starts with a value stored inside an array?

#1

Example;

let vowel = ["a", "e", "i", "o", "u"];
if (word.startsWith(vowel[0], 0)){
    answer = word.concat("yay");
    return answer;
    // the goal is to keep the first letter in place, while adding "ay" to the end.
  }

I’m working on piglatin translator and was hoping to use the same solution for other special situations, like prefixes.

#2

So in case anyone wants to know, I found out a way that works pretty good! Here’s how it’s done people!

let vowel = ["a", "e", "i", "o", "u"];
for (let i = 0; i <= word.length; i++){
    for(let v = 0; v <= vowel.length; v++){
      if (word[0] == vowel[v]){
        // code goes here
      }
    }
  }
1 Like
#3

What if you did something like this:

if (vowels.includes(str.charAt(0))) {
     //  do something here
}
1 Like
#4

yeah, that would work too! I wonder if chatAt would still work for the other situations in the translator, such as arrays with more longer values? Okay, so after testing it out, this method doesn’t work with the other situations, examples below. But yes, for the vowels (1 letter values), that works great!

let duoPrefix = ["bl", "br"]
let trioPrefix = ["scr", "sch"]
#5

Can’t you just find the first vowel in the word then split it there?

Set an index, assuming there isn’t a vowel in the word:

 const vowelArray = ['a', 'e', 'i', 'o', 'u'];

Then change the word to an array so you have more methods to work with. After that you can bring it back together as a string.

Then .foreach() to loop over each of the vowels in the vowelArray:

vowelArray.forEach( (vowel) => {

// if the word includes any of the vowels
    if(word.includes(vowel)) {
     
      // if so, then check to see if the index of that vowel is the 0, or the first one
      if(word.indexOf(vowel) === 0){

        // if so return the word
        return word + "yay"

      // else if it includes it and the vowel is deeper in the word 
      // than the first letter, reset the vowelIndex
      } if(word.indexOf(vowel) < vowelIndex || vowelIndex === -1) {
        vowelIndex = word.indexOf(vowel);
      }
    }
      //  When your finished looping through all of the vowels return the word. 
      return console.log(`the word is: ${word} and the vowelIndex is: ${vowelIndex}`)
})