- 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 within a string JavaScript
We are required to write a JavaScript function that takes in a string that might contain spaces. Our function should first split the string based on the spaces and then reverse and join and return the new string.
For example − If the input string is −
const str = 'this is a word';
Then the output should be −
const output = 'siht si a drow';
Example
const str = 'this is a word'; const reverseWords = (str = '') => { const strArr = str.split(' '); for(let i = 0; i < strArr.length; i++){ let el = strArr[i]; strArr[i] = el .split('') .reverse() .join(''); }; return strArr.join(' '); }; console.log(reverseWords(str));
Output
And the output in the console will be −
siht si a drow
Advertisements