
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reverse Words in a String using JavaScript
Problem
We are required to write a JavaScript function that takes in a string that represents a sentence.
Our function should reverse the order of words present in the string and return the new string.
It means that the last word should become the first, second last should be the second and so on.
Example
Following is the code −
const str = 'this is some random string text'; const reverseWords = (str = '') => { const strArr = str.split(' '); strArr.reverse(); const reversedStr = strArr.join(' '); return reversedStr; }; console.log(reverseWords(str));
Output
Following is the console output −
text string random some is this
Advertisements