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

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?

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