-2

Been banging my head on this. I'm trying to take user-input via form and print out their sentence backwards. It's not working and I'm not sure exactly why.

I used some code from here for the reverse string function.

I tried lots of different string reverse functions but most of them were too complicated to understand, so fairly beginner here. :) Any help would be truly appreciated.

function myFunction() {
    var sentence, text;
    sentence = document.getElementById("numb")
    sentence = sentence.replace( /^\s+|\s+$/g, " " )
    sentence = sentence.replace( /\s+/g, " " );
    
    var words = sentence.split(" ");a
        words = words.reverse();
        sentence = words.join(" ");
      document.getElementById("demo").innerHTML = text;
}
<body>
    <p >Spell a sentence backwards.</p>
    <input id="numb">
    <button type="button" onclick="myFunction()">Submit</button>
    <p id="demo"></p>
  </body>

https://jsfiddle.net/7dscpebo/

Purple Haze
  • 530
  • 7
  • 22

5 Answers5

2

A simple one-liner to reverse your string:

var forward = "Forward sentence";

var backward = forward.split("").reverse().join("");

console.log(backward);

Split the string into an array of its characters, reverse the array and then join it back up again into a string. Got the idea from here.

If you just want to reverse the order of the words in the sentence (not the characters themselves) then simply .split() and .join() with a space as follows:

var forward = "Forward sentence";

var backward = forward.split(" ").reverse().join(" ");

console.log(backward);

I've put this all together in your original example below. One modification is using an event listener rather than specifying the function in onclick which can sometimes create problems like this.

function reverseText() {
    var forward = document.getElementById("numb").value;
    var backward = forward.split("").reverse().join("");
    document.getElementById("demo").innerHTML = backward;
}

document.getElementById("btnsubmit").addEventListener("click", reverseText);
<body>
  <p>Spell a sentence backwards.</p>
  <input id="numb">
  <button id="btnsubmit" type="button">Submit</button>
  <p id="demo"></p>
</body>
abagshaw
  • 6,162
  • 4
  • 38
  • 76
  • I love the simplicity of your comment. I'm curious how do I have the answer posted to a

    . What is it that I'm missing? Here's what I have: https://jsfiddle.net/aw5tk1o3/

    – Chris M Ferguson Aug 28 '17 at 06:22
  • @ChrisMFerguson I've edited my answer to include the relevant content. Let me know if it still needs more clarification. – abagshaw Aug 28 '17 at 16:34
  • Hi, quick question, I was bringing your code into my editor and somehow it didn't work. It works in the code snippet but I couldn't get it to work. It works in JSFiddle as well: https://jsfiddle.net/j4dx36o1/ (this all my code that I have, not sure what's not working) – Chris M Ferguson Sep 04 '17 at 06:18
  • @ChrisMFerguson did you get an error? What exactly do you mean by "didn't work"? – abagshaw Sep 04 '17 at 15:47
  • I should've been more specific, when I brought your code in, pressing the button didn't return anything. Just nothing was returned upon submit. I don't know if it's the "addeventlistener" method, but something isn't working. – Chris M Ferguson Sep 05 '17 at 01:56
  • @ChrisMFerguson I'd recommend you open a new question regarding this new problem. Unfortunately there isn't much I can do without seeing the broader context of where this code is being applied. Everything works in the JSFiddle and that's all I can work with as it stands. – abagshaw Sep 05 '17 at 02:19
1

This isn't a job for regex. Just loop backwards over the string and create a new string from it, character by character.

var forward = 'this string is forward';

// create an empty string to fill with characters
var backward = '';

// loop backwards over forward
for (var i = forward.length - 1; i >= 0; i--) {
  backward += forward[i];
}

console.log(backward);

Also, you need to get the text value from your sentence element.

var forward = sentence.value;
Soviut
  • 88,194
  • 49
  • 192
  • 260
  • Thank you and how can you simply reverse the sentence, not the words themselves like: I like dogs > dogs like I – Chris M Ferguson Aug 28 '17 at 04:05
  • You would do the same thing but instead of iterating over a string, you'd iterate over an array and `.push()` items onto a new array. – Soviut Aug 28 '17 at 04:15
  • You could also just use the array `.reverse()` method. However, this will reverse the original array, it won't return a new reversed array. – Soviut Aug 28 '17 at 04:16
1

Your sentence objects is an HTMLElement, not a javascript string, so you can't call string methods on it. I think you meant something more like

var sentence = document.getElementById("numb")

if (sentence) {
    //get the value of the Input element if it exists
    var sentenceText = sentence.value

    //...the rest of your code would go in here
}
Jason
  • 31,834
  • 7
  • 59
  • 78
0

Please see my comment in the code for the fix.

function myFunction() {
    var sentence; //text is not used
    sentence = document.getElementById("numb").value; 
    //Need to get the actual value, not just the DOM
    sentence = sentence.replace( /^\s+|\s+$/g, " " )
    sentence = sentence.replace( /\s+/g, " " );
    var words = sentence.split(" ");
        words = words.reverse();
        sentence = words.join(" ");
      document.getElementById("demo").innerHTML = sentence;
}
<body>
    <p >Spell a sentence backwards.</p>
    <input id="numb">
    <button type="button" onclick="myFunction()">Submit</button>
    <p id="demo"></p>
  </body>
Long Kim
  • 490
  • 3
  • 9
0

Get the value of the input box by using document.getElementById('numb').value and reverse this using the #reverse() method for arrays:

value.split('').reverse().join('')

See demo below:

function myFunction() {
  var sentence = document.getElementById("numb").value;
  document.getElementById("demo").innerHTML = sentence.split('').reverse().join('');
}
<body>
  <p>Spell a sentence backwards.</p>
  <input id="numb">
  <button type="button" onclick="myFunction()">Submit</button>
  <p id="demo"></p>
</body>
kukkuz
  • 41,512
  • 6
  • 59
  • 95