Reversing words in a string

12,364

Solution 1

Assuming you are reversing (I'm sure this'll still help if you're not).

var original = '1 3 2';
var reversed = original.split(' ').reverse().join(' ');

Solution 2

Here's the basic idea, no need to import jQuery:

var words = "1 3 2"

var i=words.length;
i=i-1;

var reversedwords=""; 
for (var x = i; x >=0; x--)
{
    reversedwords +=(words.charAt(x));
}

alert(reversedwords) // "2 3 1"

This would also work in reversing the string "string" to "gnirts"

Share:
12,364
user270158
Author by

user270158

Updated on July 24, 2022

Comments

  • user270158
    user270158 almost 2 years

    does anybody know how can I sort words in string using javascript, jquery.

    For example I have this:

    var words = "1 3 2"
    

    Now I want to reverse it to this:

    var words = "2 3 1"
    

    Thanks

  • user270158
    user270158 about 14 years
    im sorry, this is cool, but in my case i need reversing of string
  • user270158
    user270158 about 14 years
    Excellent! Thank you very much
  • Christopher Tokar
    Christopher Tokar about 14 years
    If you had the string "132" this solution would not work because there would not be spaces to split on. However if all you are doing is sorting numbers in the format in your question, yes this solution is simpler.
  • Andy E
    Andy E about 14 years
    @ChrisTek: In that case, you could do string.split("").reverse().join("");. You could do that anyway, even for the example string given.