logo
logo

Reverse Words In A String

Lesson
Given a string, write a function called
reverseWords
that reverses the order of the words in a given string, without changing the order of the characters within each word. For example, if the input string is
"The quick brown fox"
, the output string should be
"fox brown quick The"
.

Video Solution

Traditional Looping Solution

function reverseWords(str) {
  // Split the string into an array of words
  let words = str.split(" ");
  let reversedWords = [];

  // Reverse the order of the words
  for (let i = words.length - 1; i >= 0; i--) {
    reversedWords.push(words[i]);
  }

  // Join the reversed words back into a string
  return reversedWords.join(" ");
}

Using Array Builtins

Another approach is to use javascript's built-in reverse() function along with the split and join function to achieve the same result:

function reverseWords(str) {
    return str.split(" ").reverse().join(" ");
}
First, the
split(" ")
method is used to split the input string into an array of words, where each word is an element of the array. This separates the string into substrings at each space character.
Then, the
reverse()
method is used to reverse the order of the elements in the array. This method modifies the original array in place, meaning that it reverses the order of the words in the array.
Finally, the
join(" ")
method is used to join the reversed array of words back into a string. This method concatenates all elements of an array into a string, using the provided separator in this case a space character.

By using this approach, you can achieve the same result of reversing the order of the words in the string without changing the order of the characters within each word. The overall time complexity of this solution is O(n) as it iterates through the string once.

It's important to note that this solution assumes that the input string does not contain multiple spaces between words, if the input string contains multiple spaces between words it will cause unexpected results.