My current progress is:
function pigIt(str) {
//split the string into an array of words
let words = str.split(" ");
//iterate through the array of words
for (let i = 0; i < words.length; i++) {
//loop through individual words
for (let j = 0; j < words.length; j++) {
//get the first word in the array
let firstWord = words[0];
//get the first character in the first word
let firstChar = firstWord[0];
//create a new word without the first character
let unshiftedWord = firstWord.unshift(0);
//move the first character to the end
let newWord = unshiftedWord.push(firstChar) + "ay";
return newWord;
}
}
}
console.log(pigIt('Pig latin is cool'));
At this point, my goal is to simply return "igPay"
. Later on, I will concatenate the strings to form a new one.
However, there's an issue with firstWord.unshift(0);
. It's showing the error:
TypeError: firstWord.unshift is not a function.
Even though .unshift() is a function according to MDN documentation, it's not working here. Why might that be?
Once I manage to generate a new word, I can combine the newWords
to create a newString
. There must be a more efficient way than using separate loops for each word.
EDIT: My intention is to write this function using traditional function declaration, rather than arrow notation.
EDIT 2 With @Ori Drori's solution in place, my updated function looks like:
function pigIt(str) {
newString = str.replace(/(\S)(\S+)/g, '$2$1ay');
return newString;
}
console.log(pigIt('Pig latin is cool'));
Surprisingly, it works - although I'm still puzzled by what
str.replace(/(\S)(\S+)/g, '$2$1ay');
actually accomplishes.