Skip to content

Instantly share code, notes, and snippets.

@jeffchiucp
Forked from willread/reverseWords.js
Created April 3, 2018 18:23
Show Gist options
  • Save jeffchiucp/6c29aa106b8468277cf459b6500dfa72 to your computer and use it in GitHub Desktop.
Save jeffchiucp/6c29aa106b8468277cf459b6500dfa72 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");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment