Questions on solutions for Pig Latin exercise

Hi all -
After passing the Pig Latin test, I wanted to review the answers posted on this forum. Found more advance answers than what i came up with, but they did also raise some questions. Link to the exercise below
FCC challenge guide Pig latin

I don’t really understand the use of “length” on solution #3. Could someone explain it to me please?

function translatePigLatin(str) {
  if (str.match(/^[aeiou]/)) return str + "way";

  const consonantCluster = str.match(/^[^aeiou]+/)[0];
  return str.substring(consonantCluster.length) + consonantCluster + "ay";
}

// test here
translatePigLatin("consonant");

Another question, and this one is for solution 4 (below). The first replace focuses on a vowel at the beginning of the string whereas the second one refers to consonants. The question is, do we have to write one after the other. It seems to me we are doing str.replace(code).replace(code). is this right? In advance, thanks for the guidance.

function translatePigLatin(str) {
  return str
    .replace(/^[aeiou]\w*/, "$&way")
    .replace(/(^[^aeiou]+)(\w*)/, "$2$1ay");
}

// test here
translatePigLatin("consonant");

This grabs letters from the beginning of the string until the first vowel. So for the string “blow”, the first consonant cluster would be “bl”.

You can read up on substring here: String.prototype.substring() - JavaScript | MDN

Using the “blow” example again, consonantCluster will be "bl", which has a length of 2. So it evaluates as "blow".substring(2)", which is "ow". In other words it gets the rest of the string after the first consonant cluster.

1 Like

Hi @veronicarbulu !

When posting full working solutions please wrap your solutions in [spoiler] tags.

I have edited your post.

1 Like

Thank you so much. I didn’t know how to do that. I appreciate it!

Thanks so much for taking the time to explain this. Two things:
1.- why do we need [0] after the consonant RegExp in str.match? Can we skip it?

const consonantCluster = str.match(/^[^aeiou]+/)[0];

2.- To make sure I understand correctly, you are saying, I need “length” so that I can get the rest of the string after the consonantCluster? But wouldn’t length give a number only?
I’m sorry if I’m repetitive; I’m just trying to fully understand this.
Thanks for the link!

str.substring(consonantCluster.length)

match returns an array

substring takes a number as argument

1 Like

Thank you so very very much!!!
Totally makes sense now. Much appreciated!!!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.