Skip to content

Instantly share code, notes, and snippets.

@jialinhuang00
Last active October 15, 2017 01:07
Show Gist options
  • Select an option

  • Save jialinhuang00/fe3a072f42f343eb3e380d40bc129f05 to your computer and use it in GitHub Desktop.

Select an option

Save jialinhuang00/fe3a072f42f343eb3e380d40bc129f05 to your computer and use it in GitHub Desktop.
/*-----------------------------------------------------------------------------
1.reverse every word in the sentence.
2.the orders between words do not change.
the reference used at the second function is from UdemyCourse: LearningAlgorithmsInJavascriptFromScratch
-----------------------------------------------------------------------------*/
function reverseWords(str) {
return str.split('').reverse().join('');
}
reverseWords('Coding Javascript');
// 'tpircsavaJ gnidoC'
// my code is totally wrong cus it's to reverse the words
// rather than reverse the sentences
function reverseWords2(str) {
var arr = str.split(' ');
var reversedWordsArr = [];
arr.forEach(word => {
reverseWord = '';
for (var i = word.length - 1; i >= 0; i--) {
reverseWord += word[i];
}
reversedWordsArr.push(reverseWord);
});
return reversedWordsArr.join(' ');
}
reverseWords2('Coding Javascript');
// 'gnidoC tpircsavaJ'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment