OBJECTIVE Given a string, translate the string into PigLatin (if the string starts with a vowel, append "way" to end of string - else look for the first vowel and take all preceding letters and place on the end of str, add "ay").
CODE
function translate(str) {
//list vowels
var vowel = ['a', 'e', 'i', 'o', 'u'];
//if first letter = vowel, add 'way' to end of sentence
// else return all letters before first vowel and append to end (with 'ay')
for (var i = 0; i < str.length; i++) {
if (vowel.indexOf(str[0]) > -1) {
return str + 'way';
} else {
return str.substr(i+1) + str.slice(0,i+1) + 'ay';
}
}
}
translate("dresser");
QUESTIONS
The problem is that your code will always return from the loop during the first iteration. i
will never be greater than 0.
What you should do (for starters) is remove the check from inside the loop. Like this:
function translate(str) {
//list vowels
var vowel = ['a', 'e', 'i', 'o', 'u'];
//if first letter = vowel, add 'way' to end of sentence
if (vowel.indexOf(str[0]) > -1) {
return str + 'way';
}
// else return all letters before first vowel and append to end (with 'ay')
for (var i = 0; i < str.length; i++) {
if (vowel.indexOf(str[i]) > -1) {
return str.substr(i) + str.slice(0,i) + 'ay';
}
}
}
This code should do the trick.