Created
August 24, 2012 01:57
-
-
Save willread/3444673 to your computer and use it in GitHub Desktop.
Reverse the words in a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Reverse words in a string | |
var reverseWords = function(sentence){ | |
var words = sentence.split(" ").reverse(); // Split the sentence into an array of words and reverse it | |
var string = ""; | |
for(word in words) | |
string += (word > 0 ? " " : "") + words[word]; // Concatenate each word to the output and add spaces where required | |
return string; | |
} | |
// Outputs: "backwards better look really would string This" | |
reverseWords("This string would really look better backwards"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could this be made into an NPM module?