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