javascriptjquerystringsorting

Reversing words in a string using JavaScript


How can I sort words in string using JavaScript with jQuery?

For example I have this:

var words = "1 3 2"

Now I want to reverse it to this:

var words = "2 3 1"

Solution

  • 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(' ');