Here is the code to translate a sentence to Pig Latin in Javascript:
index.tsx
functionpigLatin(sentence) {
// split sentence into an array of wordsvar words = sentence.split(" ");
// define vowelsvar vowels = ["a", "e", "i", "o", "u"];
// define an array to hold Pig Latin wordsvar pigLatinWords = [];
// loop through each word in the arrayfor (var i = 0; i < words.length; i++) {
// get the current word and convert it to lowercasevar word = words[i].toLowerCase();
// check if the word starts with a vowelif (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 sentencevar pigLatinSentence = pigLatinWords.join(" ");
// return the Pig Latin sentencereturn 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"