Skip to content

Instantly share code, notes, and snippets.

@usrrname
Last active November 29, 2019 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save usrrname/1c4e6230cbd189df1ed0de18a40479a0 to your computer and use it in GitHub Desktop.
Save usrrname/1c4e6230cbd189df1ed0de18a40479a0 to your computer and use it in GitHub Desktop.
Reverse all words in a string
const reverseWords1 = (string) => {
let newString = ' ';
let items = string.split(' ');
let results = '';
for (let i=items.length; i>=0; i--) {
results += items[i] + newString;
String(results)
}
return results;
}
reverseWords1('man bites dog');
// this first version prepends every result with undefined
const reverseWords2 = (string) => {
const items = string.split(' ');
const results = items.reverse().toString();
return results.replace(/,/g , ' ');
}
reverseWords2('man eat dog');
//much better
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment