make a function that takes in a sentence as a string and moves the first letter of every word to the end of the word, and then adds "ay" to the end of every word, and returns the string in javascript

You can make a function that takes in a sentence as a string and moves the first letter of every word to the end of the word, and then adds "ay" to the end of every word, and returns the string by following these steps:

index.tsx
function pigLatin(sentence) {
  // Split the sentence into an array of words
  let words = sentence.split(" ");
  
  // Loop through each word of the array
  for (let i = 0; i < words.length; i++) {
    // Move the first letter of the word to the end of the word and add 'ay'
    words[i] = words[i].substring(1) + words[i].charAt(0) + "ay";
  }
  
  // Join the modified array back into a string and return it
  return words.join(" ");
}
439 chars
14 lines

This function works by first splitting the input sentence into an array of words using the split() method. It then loops through each word of the array using a for loop.

For each word, it takes the first letter of the word using charAt(0), removes it from the original word using substring(1), and then appends the first letter and "ay" to the end of the word. The modified word is then replaced back into the words array.

Finally, the modified words array is joined back into a single string using the join() method and returned from the function.

gistlibby LogSnag