1

so I need to be able to enter a string and have it reversed. I must have one library JS file and one regular JS file. Here is my library JS file:

function reverseString(string) {
    var reversedString= "";
    for(var i = string.length -; i >=; --i) {
    reversedString = reversedString + string[i];
    }
    return reversedString;
}

and here is my regular one

var stringEntered = prompt("Enter a string:")
var newString = reverseString(stringEntered);
document.write("the reverse of the string \" + stringEntered + \ " is \" + newString + ".")

I entered it the exact same way my professor showed us, and I when I try to run my HTML file (which is coded to call both these files), nothing happens. What am I missing?

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
Tori Volk
  • 11
  • 1
  • Your method for reversing the string works but there's an easier way: `str.split('').reverse().join('')` - this code does the same as your loop but it first creates an array of each character (splitting per character), then reverses the array and joins it back, this way you won't have to loop ;) Also - show us your HTML file, there could be a typo in there that we can't see which causes the JS not to be executed. – SidOfc May 21 '15 at 07:52

2 Answers2

2

There're a lot of syntax issues. Here's a working code:

function reverseString(string) {
  var reversedString = "";

  // This loop had a lot of basic syntax issues and also
  // "i" was starting from the length value, while a string
  // is a character array and array indexes start from 0 instead of 1
  for (var i = string.length - 1; i >= 0; --i) {
    reversedString = reversedString + string[i];
  }
  return reversedString;
}

var stringEntered = prompt("Enter a string:");
var newString = reverseString(stringEntered);

// Here I found a mess of "/" characters
// I've changed the horrible document.write with alert so you can check the result without opening the debugger...
alert("the reverse of the string " + stringEntered + " is " + newString + ".")
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
0

Here is a concise method of reversing a string:

function reverseString(string) {
   return string.split('').reverse().join('');
}

var str = prompt("Enter a string", "a racecar dad");
alert(reverseString(str));

Turn it into an array, reverse the array, turn it back into a string.

Edit: Sorry, didn't see @SidneyLiebrand's comment telling you to do the same.

Rob M.
  • 35,491
  • 6
  • 51
  • 50