Reverse a Phrase

Ask the user for a phrase and then print out a version of that phrase with the letters reversed back to front. For an example click here

The magic here is done with arrays, a list of similar elements that can be accessed by their location in the array. For example, you might have an array of cars, declared like this:

var cars [];
cars = ["Chevy", "Toyota", "VW", "Ford"];

Then

document.write( cars[2] );

will print "VW" (arrays start with 0)

One approach to Reverse-a-Phrase is to use two arrays, one to take all the letters from the initial phrase, and then to walk thru this array back to front, copying the letters, one by one, into the second array.

There are other ways to do this, see if you can try different algorithms.

NOTE: This is the most common question asked on technical interviews - "Write a program to reverse a phrase"

Directions

  1. Set up your form with these Page Elements:
    * An input field - for the phrase.
    * A buttons - to trigger the action.
    * A text label - on which to show the results.

  2. Setup Your Code
    Create a pair of arrays

    var letters1[];
    var letters2[];

    Create a function reverseIt() which will do the work.

  3. Break up the Phrase
    Take the phrase from the input field, break it up into individual characters and move it to the first array. Use a for loop and the charAt(i) function to walk through the phrase.

  4. Reverse it. Now walk thru the first array back to front, copying the letters, one by one, into the second array.

  5. Turn the 2nd array into a string, using the join method:

    reversePhrase = letters2.join("");

  6. Show the new Phrase in your label

  7. Clean the code until you've fixed all the bugs, and then run the form.
    When done, ask your teacher to upload the project to your public folder, so your friends and family can enjoy it.






(c) 2017 by Code Craft Academy