1

I am trying to write code to reverse my text. Ex: Apple is Fruit --> Fruit Is Apple. I written code which is not working. Thanks for the help!

JSFiddle

<html>
<body>
  <center>
    <form>
      <textarea autocomplete="off" cols="30" id="TextInput1" name="message" rows="5" style="border: 3px solid #73AD21; width: 40%;"></textarea>
      <textarea autocomplete="off" cols="30" id="TextInput2" name="message" rows="5" style="border: 3px solid #73AD21; width: 40%;"></textarea><br />
      <input id="WhiteSpaceRemove" onclick="myFunction()" style="border: 3px solid #73AD21;" type="button" value="Convert" />
    </form>
  </center>
  <script>
    function myFunction() {
      var x = document.getElementById("TextInput1").value;

      document.getElementById("TextInput2").innerHTML = x.reverse();
      document.getElementById("CopyButton").value = "Copy Text!";
    }
  </script>
</body>
</html>
blex
  • 24,941
  • 5
  • 39
  • 72
santosh
  • 742
  • 8
  • 19

1 Answers1

4

The reverse() method only exists on the array prototype. Since you want to reorder them in groups of words (and not by character), you will need to split x by an empty space, and then rejoin it thereafter:

document.getElementById("TextInput2").innerHTML = x.split(' ').reverse().join(' ');

This basically splits your sentence up into individual words, and then rejoins it in a reverse order after that.

See proof-of-concept:

function myFunction() {
  var x = document.getElementById("TextInput1").value;

  document.getElementById("TextInput2").innerHTML = x.split(' ').reverse().join(' ');
}
<form>

  <textarea autocomplete="off" cols="30" id="TextInput1" name="message" rows="10" style="border: 3px solid #73AD21; width: 40%;">Lorem ipsum dolor sit amet</textarea>

  <textarea autocomplete="off" cols="30" id="TextInput2" name="message" rows="10" style="border: 3px solid #73AD21; width: 40%;"></textarea><br />

  <input id="WhiteSpaceRemove" onclick="myFunction()" style="border: 3px solid #73AD21;" type="button" value="Convert" />

</form>
Terry
  • 63,248
  • 15
  • 96
  • 118