![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ] ]
Advertisements