Request for help in fixing my code for PigLatin challenge

Request for help in fixing my code for PigLatin challenge
0

#1

Hello. Could I request some assistance with the pigLatin algorithm challenge? Am I on the right track, and if so, how do I get rid of the infinite while-loop I’ve unintentionally set up. Thanks!

(Code here):

function translatePigLatin(str) {
   var regex = /[aeiou]/gi;
   var i = 0;
   if (str[0].match(regex)) {
      str.push("way");
   } else {
      while (!str[i].match(regex)) {
         var sliced = str.slice(i, i+1);
         str.push(sliced);
         i++;
   }
   str += 'ay';
   return str;
}

translatePigLatin("consonant");

#2

First, you are missing an } for your while loop. Once you fix that, you get an error message in your console like:

TypeError: str.push is not a function
at translatePigLatin:9:14

Why? Because str is a string and trying to use push on a str is not valid. The push function works with arrays.


#3

Thanks! Although I’m able to move the first character in the str to the end (see below), I am having difficulty writing a for or while loop that iterates over consonant clusters. I wondered if I’m on the right track, or if I should try a different approach.

var str = "school";
var i = 0;
var regex = /[aeiou]/gi;


   var sliced = str.slice(i, i+1);
   str = str.slice(1) + sliced;
   i++;

#4
var str = "school";
var i = 0;
var regex = /[aeiou]/gi;
var consonantCluster = '';
while (!regex.test(str[i])) {
   consonantCluster += str[i++];
}
console.log(consonantCluster); // 'sch'

OR

var str = "school";
var regex = /[aeiou]/gi;
for (var i = 0, consonantCluster = ''; i < str.length; i++) {
  if (regex.test(str[i])) break;
  consonantCluster += str[i];
}
console.log(consonantCluster); // 'sch'

#5

Hello. My code now produces correct output for strings that begin with a vowel. It produces incorrect output for strings that begin with a consonant.

function translatePigLatin(str) {
   var i = 0;
   var regex = /[aeiou]/gi;
   var cCluster = '';
  
   if (str[0].match(regex)) {
     str += 'way';
   } else {
     
     while (!regex.test(str[i])) {
       cCluster += str[i];
       str = str.slice(cCluster.length-1) + cCluster + 'ay'; 
     }
   }
   return str;
}

translatePigLatin(“choose”); //Output: hoosecaychay


#6

Your assignment to str inside the while loop is a problem and you need to increment your i variable inside the while loop. Also, your slice should start at cCluster.length.


#7

I’m now meeting four of the five requirements. I am still unsure of how to remove consonant clusters from the string.

function translatePigLatin(str) {
   var i = 0;
   var regex = /[aeiou]/gi;
   var cCluster = '';
  
   if (str[0].match(regex)) {
     str += 'way';
   } else {
     
     while (!regex.test(str[i])) {
       cCluster += str[i++];
       str = str.slice(cCluster.length) + cCluster + 'ay';
       i++;
     }
   }
   return str;
}

translatePigLatin("straw"); //Output = trawsay