Jelani Thompson Jelani Thompson - 6 months ago 12
Javascript Question

.indexOf() not working with specific vowel

So I'm making an algorithm that converts input to Pig Latin. Here's what I have so far:

function translatePigLatin(str) {
var consonantCluster = [];
var vowels = ['a', 'e', 'i', 'o', 'u'];
var stringArray = str.split('');

if (vowels.indexOf(stringArray[0]) === 0) {
stringArray.push('w', 'a', 'y');
stringArray = stringArray.join('');
console.log(stringArray);
return stringArray;
}

for (var i = 0; i < stringArray.length; i++) {
if (vowels.indexOf(stringArray[i]) == -1) {
consonantCluster.push(stringArray[i]);
stringArray.push(stringArray[i]);
} else {
stringArray.push('a', 'y');
stringArray.splice(0, consonantCluster.length);
stringArray = stringArray.join('');
console.log(stringArray);
return stringArray;
}
}

return str;
}
translatePigLatin("eight");


It works for the most part. However, when I hand a word to the function that's a vowel, it doesn't work if it doesn't begin with the letter A. Instead it returns
ay
as opposed to what it should return if the word starts with a vowel
way
. Any help would be appreciated!

Answer

The way you wrote line 6 you were only checking to see if the first letter of stringArray was equal to the first value of the vowels array (index = 0).

If you change (vowels.indexOf(stringArray[0]) === 0) to if (vowels.indexOf(stringArray[0]) !== -1) { you will be checking to see if the first letter in the stringArray matches any of the values in the vowels array.

Comments