
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
Reversing and Preserving Spaces in JavaScript
Problem
We are required to write a JavaScript function that takes in a sentence string, str, as the first and the only argument.
Our function is supposed to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
For example, if the input to the function is −
const str = 'this is some sample string';
Then the output should be −
const output = 'siht si emos elpmas gnirts';
Example
Following is the code −
const str = 'this is some sample string'; const reverseWords = (str = '') => { return str.trim() .split(/\s+/) .map((s) => { let res = '' for (let i = s.length-1; i >= 0; i--) { res += s[i] } return res }) .join(' '); } console.log(reverseWords(str));
Output
Following is the console output −
siht si emos elpmas gnirts
Advertisements