- 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 a string while maintaining the position of spaces in JavaScript
Problem
We are required to write a JavaScript function that takes in a string that might contain some spaces.
Our function should reverse the words present in the string internally without interchange the characters of two separate words or the spaces.
Example
Following is the code −
const str = 'this is normal string'; const reverseWordsWithin = (str = '') => { let res = ""; for (let i = str.length - 1; i >= 0; i--){ if(str[i] != " "){ res += str[i]; }; if(str[res.length] == " "){ res += str[res.length]; }; }; return res; }; console.log(reverseWordsWithin(str));
Output
gnir ts lamron sisiht
Advertisements