
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 −
const str = 'this is a string';
Example
Following is the code −
const str = 'this is a string'; const reverseWordOrder = (str = '') => { const strArr = str.split(' '); let temp = ''; const { length } = strArr; 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));
Output
Following is the output on console −
this is a string [ [ 1, 0, 0, 0, 0 ], [ 0, 1, 0, 0, 0 ], [ 0, 0, 1, 0, 0 ], [ 0, 0, 0, 1, 0 ], [ 0, 0, 0, 0, 1 ] ]
- Related Articles
- Reversing the even length words of a string in JavaScript
- Reversing words in a string in JavaScript
- Reversing words within a string JavaScript
- Reversing words present in a string in JavaScript
- Reversing the words within keeping their order the same JavaScript
- Reversing the prime length words - JavaScript
- Arranging words in Ascending order in a string - JavaScript
- Reversing vowels in a string JavaScript
- Reversing a string while maintaining the position of spaces in JavaScript
- Reversing alphabets in a string using JavaScript
- Replace words of a string - JavaScript
- Finding the number of words in a string JavaScript
- Swapping adjacent words of a String in JavaScript
- Reversing a string using for loop in JavaScript
- Reversing consonants only from a string in JavaScript

Advertisements