Pig Latin - regex to grab first consonant or first 2 consonants

I am splitting my code up to handle words that begin with vowel versus those that begin with a consonant or consonant cluster.

The former can easily be solved by adding “way” to the end of str. The latter is the one I am running into problems with.

First, I need a regex that returns the first (and only first) or first two (and only first two) consonant(s) so I can split the str at that point, move it to the end, then rejoin with “ay” at the end. But I cannot get that regex to work.

Would appreciate a review of my regexpcons code to see what I am doing wrong?

Thank you.

Your code so far


function translatePigLatin(str) {

  //if word begins with a vowel, just add "way" to end of str
  //regex to capture word beginning with vowel:
  let regexpvow = /^[aeiou]/;
  let regexpcons = /^(?=[^aeiou])/;

  if(regexpvow.test(str)){
      return str + "way";
  //Else if consonant
    // move that consonant or consonant cluster (consonant + consonant) to end of str
    // add "ay" to str
  }else {
    return str.match(regexpcons); 
   //just checking to see what it returns before continuing on with actual solution
  }



  // return str;
}

EDIT: I updated code to: let regexpcons = /^(?=[^aeiou])+/g; but this still did not work.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin

1 Like

OK. Changed it again. This worked:

let regexpcons = /^([^aeiou])+/g;

1 Like

And my final code in case anyone is still reading:

function translatePigLatin(str) {

  //if word begins with a vowel, just add "way" to end of str
  //regex to capture word beginning with vowel:
  let regexpvow = /^[aeiou]/;
  let regexpcons = /^([^aeiou])+/g;
  // console.log("This is regexpcons: " + str.match(regexpcons)[0]);
  // console.log("This is the length of regexpcons: " + (str.match(regexpcons)[0]).length);

  if(regexpvow.test(str)){
      return str + "way";
  //Else if consonant
    // move that consonant or consonant cluster (consonant + consonant) to end of str
    // add "ay" to str
  }else {
    let strasarr =  (str + str.match(regexpcons) + "ay").split("");
    strasarr.splice(0,str.match(regexpcons)[0].length);
    return strasarr.join("");
  }

}
2 Likes