Skip to content

Instantly share code, notes, and snippets.

@willread
Created August 24, 2012 01:57
Show Gist options
  • Select an option

  • Save willread/3444673 to your computer and use it in GitHub Desktop.

Select an option

Save willread/3444673 to your computer and use it in GitHub Desktop.
Reverse the words in a string
// 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");
@haykam821
Copy link
Copy Markdown

Could this be made into an NPM module?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment