Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing words in a string

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

like image 222
user270158 Avatar asked Feb 17 '10 08:02

user270158


People also ask

Does Reverse () work on strings?

reverse() works like reversing the string in place. However, what it actually does is create a new string containing the original data in reverse order.


2 Answers

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"

like image 43
Christopher Tokar Avatar answered Oct 13 '22 00:10

Christopher Tokar


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(' ');
like image 67
Steve Avatar answered Oct 13 '22 00:10

Steve