JavaScript Program to Reverse Words in String
str.split(' ').reverse().join(' ') to reverse the words in a string in JavaScript, for example: const reversed = str.split(' ').reverse().join(' ');.Examples
How to Think About It
Algorithm
Code
function reverseWords(str) { return str.split(' ').reverse().join(' '); } const input = "JavaScript is fun"; const output = reverseWords(input); console.log(output);
Dry Run
Let's trace the input "JavaScript is fun" through the code.
Split string into words
"JavaScript is fun".split(' ') => ["JavaScript", "is", "fun"]
Reverse the array
["JavaScript", "is", "fun"].reverse() => ["fun", "is", "JavaScript"]
Join reversed words
["fun", "is", "JavaScript"].join(' ') => "fun is JavaScript"
| Step | Words Array |
|---|---|
| After split | ["JavaScript", "is", "fun"] |
| After reverse | ["fun", "is", "JavaScript"] |
| After join | "fun is JavaScript" |
Why This Works
Step 1: Splitting the string
Using split(' ') breaks the string into an array of words separated by spaces.
Step 2: Reversing the array
The reverse() method reverses the order of elements in the array, changing the word order.
Step 3: Joining words back
Finally, join(' ') combines the reversed words into a single string with spaces.
Alternative Approaches
function reverseWordsLoop(str) { const words = str.split(' '); let reversed = ''; for (let i = words.length - 1; i >= 0; i--) { reversed += words[i] + (i === 0 ? '' : ' '); } return reversed; } console.log(reverseWordsLoop('hello world'));
function reverseWordsRec(str) { const words = str.split(' '); if (words.length <= 1) return str; return reverseWordsRec(words.slice(1).join(' ')) + ' ' + words[0]; } console.log(reverseWordsRec('hello world'));
Complexity: O(n) time, O(n) space
Time Complexity
Splitting, reversing, and joining each take linear time proportional to the number of words, so overall time is O(n).
Space Complexity
Extra space is used to store the array of words, so space complexity is O(n).
Which Approach is Fastest?
The built-in split-reverse-join method is fastest and most readable; loops and recursion are slower and more complex.
| Approach | Time | Space | Best For |
|---|---|---|---|
| split-reverse-join | O(n) | O(n) | Simple and fast for most cases |
| for loop reversal | O(n) | O(n) | Clear manual control, educational |
| recursion | O(n^2) | O(n) | Demonstrating recursion, less efficient |
split, reverse, and join together for a simple and fast solution.