2

Was wondering if you can reverse a string and still maintain the order.

Below is a function that returns "dlroW olleH" and I want to return "olleH dlroW"

var myFunction = function() {
var userdata = document.getElementById('data').value,
    uRev = userdata.split("").reverse().join("");
document.getElementById('results').innerHTML = uRev;
};

Thanks!

billystacks
  • 33
  • 1
  • 4
  • @JamesDonnelly That question is about reversing the whole string, not one word at a time. See the duplicate I found. – Barmar Oct 28 '13 at 15:48

6 Answers6

2

Reverse the words and then the characters:

var myFunction = function() {
    var userdata = document.getElementById('data').value,
    uRev = userdata.split(" ").reverse().join(" ").split("").reverse().join("");
    document.getElementById('results').innerHTML = uRev;
};

Example JSFiddle

Moob
  • 14,420
  • 1
  • 34
  • 47
1
function reverseString(s){
    return s.split("").reverse().join("");
}

function reverseEachWord(s) {
    return s.split(" ").map(reverseString).join(" ");
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Didn't see your answer :) lost between all the others. The other answers reverse the order of the words, then the string (Hello World -> World Hello -> olleH dlroW). This version reverses each individual word. It might be better suited. – Tibos Oct 28 '13 at 15:52
0
alert(userdata.split(" ").reverse().join(" ").split("").reverse().join(""));
aross
  • 3,325
  • 3
  • 34
  • 42
0

first split your string in an array of words using split(" "), then split each array segment using the method above.

Nzall
  • 3,439
  • 5
  • 29
  • 59
0

Try this,

var myFunction = function() {
    var resArr=[];
    var userdata = document.getElementById('data').value,
    uRev = userdata.split("");
    for (var i=0;i<uRev.length;i++){
      resArr.push(uRev[i].reverse());
    }

    document.getElementById('results').innerHTML = resArr.join('');
};
Anand Jha
  • 10,404
  • 6
  • 25
  • 28
0
var test = 'Hello World';

alert( 
    test.replace(
        /\w+/g , 
        function(a){return a.split('').reverse().join('');}
    )
);
MC ND
  • 69,615
  • 8
  • 84
  • 126