Homework

Pig Latin translator

At the bottom of this page is a function. Don't worry if you don't understand how this function works! It's pretty complicated and uses some techniques we've not covered yet.

The great thing about functions is that you don't have to know how they work on the inside to be able to use them in your code!

This function is called translateToPigLatin and it's based on the pretend language Pig Latin that children sometimes learn to share secret messages with each other.

You can give this function a sentence and it will return the Pig Latin version of that sentence:

translateToPigLatin('Hello there') // Returns 'ellohay erethay'
translateToPigLatin('what is going on') // Returns 'atwhay isway oinggay onway'

Your task

Your task is to use this function in a website. Build a website with a text-box and a button.

The button should say 'translate' and when you click the button it translates the contents of the text box into Pig Latin (using the function below) and displays the translation on the page.

The function

Here's the code for the function - just copy/paste this into your JavaScript file.

function translateToPigLatin(text) {
    const vowels = ['a', 'e', 'i', 'o', 'u']
    const words = text.toLowerCase().split(' ')
    const result = []
    for (const word of words) {
        if (vowels.includes(word[0])) {
            result.push(word + "way")
        } else {
            const firstMatch = word.match(/[aeiou]/g) || 0;
            const vowelIndex = word.indexOf(firstMatch[0]);
            const newWord = word.substring(vowelIndex) + word.substring(0, vowelIndex) + "ay";
            result.push(newWord)
        }
    }
    return result.join(' ')
}

Last updated