Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Reversing the order of words of a string in JavaScript
We are required to write a JavaScript function that takes in a string as the only argument.
The function should reverse the order of the words in the string and return the new string.
The only condition is that we cannot use the inbuilt array method reverse().
For example −
If the input string is −
const str = 'this is a string';
Then the output string should be −
string a is this
Using Manual Array Reversal
We can split the string into words, manually reverse the array without using the built-in reverse() method, and join back:
const str = 'this is a string';
const reverseWordOrder = (str = '') => {
const strArr = str.split(' ');
let temp = '';
const { length } = strArr;
// Manually reverse array by swapping elements
for(let i = 0; i < length / 2; i++){
temp = strArr[i];
strArr[i] = strArr[length - 1 - i];
strArr[length - 1 - i] = temp;
}
return strArr.join(' ');
};
console.log(reverseWordOrder(str));
string a is this
Using Loop to Build Reversed String
Another approach is to iterate through the words array from the end to the beginning:
const str = 'hello world javascript programming';
const reverseWordOrderLoop = (str = '') => {
const words = str.split(' ');
let reversed = '';
// Build string from last word to first
for(let i = words.length - 1; i >= 0; i--){
reversed += words[i];
if(i > 0) reversed += ' '; // Add space except for last word
}
return reversed;
};
console.log(reverseWordOrderLoop(str));
programming javascript world hello
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Manual Array Reversal | O(n) | O(n) | Medium |
| Loop Build | O(n) | O(n) | High |
Conclusion
Both methods effectively reverse word order without using the built-in reverse() method. The loop approach is more readable, while manual reversal demonstrates array manipulation techniques.
