translate sentence to pig latin in javascript

Here is the code to translate a sentence to Pig Latin in Javascript:

index.tsx
function pigLatin(sentence) {
  // split sentence into an array of words
  var words = sentence.split(" ");
  
  // define vowels
  var vowels = ["a", "e", "i", "o", "u"];
  
  // define an array to hold Pig Latin words
  var pigLatinWords = [];
  
  // loop through each word in the array
  for (var i = 0; i < words.length; i++) {
    // get the current word and convert it to lowercase
    var word = words[i].toLowerCase();
    
    // check if the word starts with a vowel
    if (vowels.indexOf(word[0]) > -1) {
      // if it starts with a vowel, just add "way"
      pigLatinWords.push(word + "way");
    } else {
      // if it starts with a consonant, move the consonant to the end and add "ay"
      pigLatinWords.push(word.slice(1) + word[0] + "ay");
    }
  }
  
  // join the array of Pig Latin words into a sentence
  var pigLatinSentence = pigLatinWords.join(" ");
  
  // return the Pig Latin sentence
  return pigLatinSentence;
}
948 chars
32 lines

To use this function, simply pass in a sentence as a string:

index.tsx
var sentence = "hello world";
var pigLatinSentence = pigLatin(sentence);
console.log(pigLatinSentence);
// Output: "ellohay orldway"
133 chars
5 lines

gistlibby LogSnag