- Trending Categories
- 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 words in a string in JavaScript
We are required to write a JavaScript function that takes in a string. The function should return a new string that has all the words of the original string reversed.
For example, If the string is −
const str = 'this is a sample string';
Then the output should be −
const output = 'siht si a elpmas gnirts';
Example
The code for this will be −
const str = 'this is a sample string'; const reverseWords = str => { let reversed = ''; reversed = str.split(" ") .map(word => { return word .split("") .reverse() .join(""); }) .join(" "); return reversed; }; console.log(reverseWords(str));
Output
The output in the console −
siht si a elpmas gnirts
Advertisements