0

I know there are probably other ways of doing this but i am really wondering why this code is not working properly. It does somewhat reverse stuff but the output it wrong. The idea is simply to type in a string in the textbox and when pressed on the button it should be reversed and in this case shown in an alertbox.

<input type="text" id="invoer"><input type="button" value="Display" onclick="reverseString()">

<script>

function reverseString() {
    var length = document.getElementById("invoer").value.length;
    var reverse = new String;
    for(i=length-1;i>=0;i--) {
        reverse += document.getElementById("invoer").value.substring(i,1);
    }
    alert(reverse);
}

</script>
Jasper Simons
  • 21
  • 1
  • 3
  • This sounds like a great time to use your browser's debugging tools. When you step through your code in your debugger, line by line as it executes, and observe the runtime values and behavior, when does it *first* do something you don't expect? What line of code was the *first* to do something wrong? What were the inputs to that line of code? What was the result? What did you expect the result to be? Why? – David Jul 15 '18 at 12:56
  • 1
    `function reverseString(input) {return input.split('').reverse().join('');}` - using native options is generally going to be better than manually shuffling all those characters around. Also don't use `new String`, just `""` will do. – Niet the Dark Absol Jul 15 '18 at 12:58

1 Answers1

0

With each iteration, you are returning the string from the beginning to the index i. Change this line:

reverse += document.getElementById("invoer").value.substring(i, 1);

to this line:

reverse += document.getElementById("invoer").value.substring(i, i+1);

This is a complete, working snippet:

function reverseString() {
  var length = document.getElementById("invoer").value.length;
  var reverse = new String;
  for(i = length - 1; i >= 0; i--) {
    reverse += document.getElementById("invoer").value.substring(i, i+1);
  }
  alert(reverse);
}
<input type="text" id="invoer"><input type="button" value="Display" onclick="reverseString()">
Wais Kamal
  • 5,858
  • 2
  • 17
  • 36
  • Alternative fix is to use `.value.substr(i,1)` - start from i and return 1 character. Or, even better, just `.value[i]` will work since strings can be accessed as arrays of characters. – Niet the Dark Absol Jul 15 '18 at 13:00