views:

103

answers:

2

Hello, 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

+3  A: 

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"

Chris Tek
Chris's right, you don't need jQuery for this.
aefxx
im sorry, this is cool, but in my case i need reversing of string
please see the updated code... this'll do the trick
Chris Tek
Excellent! Thank you very much
+4  A: 

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(' ');
Steve
It works. Great and simple. Thanks
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.
Chris Tek
@ChrisTek: In that case, you could do `string.split("").reverse().join("");`. You could do that anyway, even for the example string given.
Andy E