3

I'm currently taking an introduction CIS class at my university and one of the projects is javascript. It is split into two unrelated parts and I was able to do the second part but I'm stuck on the first one. My professor wants me to write an iteration that will display in a reverse order whatever name I write in the prompt screen. So if I write "John Smith" it will display "htims nhoj". The issue is that I have no idea how to write it.

<html>
   <body>
      <script>
         var namIn = window.prompt("Enter name:" );  
         var namAr = namIn.split("");  
         var namArLen = namAr.length;
         document.write(namAr + "<br /> Length: " + namArLen);
     </script>
   </body>
</html>
3
  • 1
    "John Smith".split("").reverse().join(""); Commented May 17, 2013 at 23:35
  • 1
    "He hasn't covered it in lecture and I can't find anything in my textbook" - you might be expected to figure this out on your own. Surely you've covered loops. Commented May 17, 2013 at 23:36
  • Does he specifically want you to cover iteration in JavaScript (for (var x in y), for (var i = 0; i < 10; i++), while (something === true) etc.) or does he just want you to reverse a string? Commented May 17, 2013 at 23:43

5 Answers 5

11

Strings in JavaScript have a function called split() which turn them in to Arrays. Arrays in JavaScript have a function called reverse() which reverse their order, and a function called join() which turn them back into Strings. You can combine these into:

"John Smith".split("").reverse().join("")

This returns:

"htimS nhoJ"

Also, and I don't know if this is a typo, but you can throw a toLowerCase() to get 100% of what your question is after:

"John Smith".split("").reverse().join("").toLowerCase()

returns:

"htims nhoj"

As for the question in your title, you can specify the direction of a for loop in the last argument like so:

var reversed = [];
var name = "John Smith".split("");
for(var i = name.length-1; i >= 0; i--) {
    reversed.push(name[i]);
}
console.log(reversed.join(""));

Which will output:

"htimS nhoJ"
Sign up to request clarification or add additional context in comments.

Comments

1

There's no need to split this string into an array. Just use the charAt() function and a simple for loop.

var name = window.prompt("Enter name:");
var reverse = "";
for (var i = name.length - 1; i >=0; i--) {
    reverse += name.charAt(i);
}
console.log(reverse)

Instead of converting the string to an array first, you're just reading the characters out of the string directly.

Comments

1

You can accomplish this by iterating only half the number of characters.

DEMO: http://jsfiddle.net/vgG2P/

CODE:

var name = "Bob Dylan".split("");

//                    The counters will meet in the middle.
//                    --------------+----------------------
//      first char   last char      |   inc  dec
// -------v-------------v-----------v----v----v
for(var i = 0, j = name.length-1; i < j; i++, j--) {

    var temp = name[i];  // Store the `i` char
    name[i] = name[j];   // Replace the `i` char with the `j` char
    name[j] = temp;      // Replace the `j` char with the `i` char we stored

}

console.log(name.join(""));  "nalyD boB"

EXPLANATION:

What we did was split the characters into an Array, and maintain two counters, one that increments from the first character at 0, and the other that decrements from the last character at .length - 1. Then simply swap the characters.

The iteration continues while your incrementing counter is less than your decrementing counter. Since they will meet in the middle, you'll end up incrementing only half the total length.


We can also build the halves of the result without using an Array:

DEMO: http://jsfiddle.net/vgG2P/1/

var name = "Bob Dylan";

var start = "", end = ""

for(var i = 0, j = name.length-1; i < j; i++, j--) {
    end = name.charAt(i) + end
    start += name.charAt(j)
}

if (i === j)
    start += name.charAt(i)

console.log(start + end);  "nalyD boB"

Comments

0

I'm assuming that your professor would not be asking you how to reverse a string if he hasn't yet introduced you to the concept of arrays and loops. Basically, a string like John Smith is just an array of characters like this:

0123456789
John Smith

Again, thinking in the sense that a string is just an array of characters, you have have 10 characters that need to be reversed. So how do you go about doing this? Well, you basically need to take the last character h from the "array" you're given and make it the first character in a new "array" you're going to create. Here's an example:

var known = 'John Smith';
var reversed = ''; // I'm making an empty string aka character array
var last = known.length - 1 // This is the index of the last character

for (var i = 0; i < known.length; i++)
{
  temp += known[last - i];
}

(You can see it working here)

So what's happening?

  • We're looping over known starting at 0 and ending at 9 (from the first character to the last)
  • During each iteration, i is incrementing from 0 - 9
  • last always has a value of 9
  • last - i will give us indexes in reverse order (9, 8, 7, ..., 0)
  • So, when i is 0, last - i is 9 and known[9] is "h"; repeat this process and you get the reversed string

Hopefully this helps explain a little better what's happening when you call reverse() on an array.

Comments

0

(1) A more straight forward way without built-in functions:

function reverse(str) {
    let reversed_string = "";
    for (let i = str.length - 1; i >= 0; i--) {
        reversed_string += str[i];
    }
    return reversed_string;
}

(2) Using ES2015 'for' helper function:

function reverse(str) {
    let reversed_string = "";
    for (let character of str) {
        reversed_string = character + reversed_string;
    }
    return reversed_string;
}

(3) Using ES6 syntax and ES5.1 reduce():

function reverse(str) {
    return str.split('').reduce((reversed, char) => char + reversed, '');
}

// reduce takes in 2 arguments. (1) arrow function, and (2) empty string.

Chances are, for an interview, that you will not able to use the built-in functions, especially for "reverse()".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.