- 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
Reverse the words in the string that have an odd number of characters in JavaScript
We are required to write a JavaScript function that takes in a string and reverses the words in the string that have an odd number of characters in them.
Any substring in the string qualifies to be a word, if either it is encapsulated by two spaces on either ends or present at the end or beginning and followed or preceded by a space.
Example
The code for this will be −
const str = 'hello world, how are you'; const idOdd = str => str.length % 2 === 1; const reverseOddWords = (str = '') => { const strArr = str.split(' '); return strArr.reduce((acc, val) => { if(idOdd(val)){ acc.push(val.split('').reverse().join('')); return acc; }; acc.push(val); return acc; }, []).join(' '); }; console.log(reverseOddWords(str));
Output
Following is the output on console −
olleh world, woh era uoy
Advertisements