Pig Latin - questions

Hi all, I’m working on Pig Latin - https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin

My code so far.

function translatePigLatin(str) {
  //checking consonant
  const consonantRex = /^[^aeiou]+/;
  //consonant => c
  const consonant = str.match(consonantRex);


  let result = str.match(consonant) === true ?
  str.replace(consonant,"")
  .concat(consonant+"way")
  :
  str.concat("ay")

return result

}

console.log(translatePigLatin("consonant"));

The result I am getting is consonantay so I guess something wrong in str.match(consonant) === true but I don’t why its not working. Please can someone tell me?

Thanks!

1 Like

Check str.match(consonant) === true.

Try to console.log(str.match(consonant)) and see if it’s equal to true

1 Like

You seem to be confused about what values are returned from the match method. I would console.log(str.match(consonant)) before the let result = line, so you understand the possibly values of it before trying to using it in the way you are currently doing.

1 Like

Hi,
Thanks for your reply.
console.log(str.match(consonant)) the result is false
I am stuck here as here the consonant is c; so I don’t know why it logs false…

1 Like

The problem with your code is in the condition str.match(consonant) === true. str.match(consonant) returns an array of matched items, and arrays in JavaScript are truthy values. So even if the array is empty (which means no match), the condition will always be false because an empty array is not equal to true.

To check if there was a match, you should check if consonant is not null. null is returned by str.match() if there was no match.

So, you need to change the condition from str.match(consonant) === true to consonant !== null.

1 Like

Ah ok, based on your reply - so str.match(consonant) will either return an array (if match found) or null (if no match found). It won’t be true no matter what. Am I correct?