Coding Challenge: Reverse the words for a given string

Navigation Menu

Given an input string, reverse the string word by word.

Here I have listed sample data for given input with expected output!

Input: "the sky is blue"
Output: "blue is sky the"
Input: "  hello world!  " Output: "world! hello" Explanation: Your reversed string should not contain leading or trailing spaces.

To solve this problem, first we will convert the string into words array and using for loop we can reverse the order of words into string!

Here is the working Solution:

const testReverseWords = (str) => {
  let wordArr = [];
  let result = '';
  wordArr = str.split(' ');
  console.log(wordArr);
  for (let i = wordArr.length - 1; i >= 0; i--) {
  	result += wordArr[i] + " "; 
  }
  return result;
}
console.log(testReverseWords('the sky is blue'));