- 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 the even length words of a string 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 even number of characters in them.
Let’s say the following is our string −
const str = 'This is an example string';
We want to reverse the even length words of the above string i.e. reverse the following words −
This is an string
Example
The code for this will be −
const str = 'This is an example string'; const isEven = str => !(str.length % 2); const reverseEvenWords = (str = '') => { const strArr = str.split(' '); return strArr.reduce((acc, val) => { if(isEven(val)){ acc.push(val.split('').reverse().join('')); return acc; }; acc.push(val); return acc; }, []).join(' '); }; console.log(reverseEvenWords(str));
Output
The output in the console will be −
sihT si na example gnirts
Advertisements