Pig Latin Challenge - Code not working as planned

Hello everyone, I thought I had a correct solution but for some reason, my code is skipping some letters. Why is that? If anybody could help me I would really appreciate it!


function translatePigLatin(str) {
var regex = /^[aeiou]/;
var regex2 = /[aeiou]/g
var regex3 = /[bcdfghjklmnpqrstvwxyz]/
var thing = str;
if (regex.test(str) === true) {
  thing = str + "way";
} else if (regex2.test(str) === false) {
   thing = str + "ay";
} else if (regex.test(str) === false) {
  var split = str.split("");
  for (var i = 0; i < split.length; i++) {
    if (regex3.test(split[i]) === true) {
      let splice = split.splice(i, 1);
      split.push(splice);
    } else if (regex3.test(split[i]) === false) {
      thing = split.join("") + "ay";
      break;
    }
  }
}
return thing;
}
console.log(translatePigLatin("california"))
// returns aioniaclfray instead of aliforniacay
console.log(translatePigLatin("glove"))
// returns lovegay instead of oveglay
console.log(translatePigLatin("schwartz"))
// returns cwartzshay instead of artzschway

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36

Challenge: Pig Latin

Link to the challenge:

Hi @monoboe ,

The code is looping through the split array and modifying the same split array inside the loop. The indexes of the elements of the split array will keep changing.
Do a console log of split[i] and you’ll see the problem.

for (var i = 0; i < split.length; i++) {
.....
let splice = split.splice(i, 1);

I think I know what I can do to fix it now. Thanks for the information, I really do appreciate it.

1 Like