Reversing the even length words of a string in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 17-Oct-2020 14:33:24
Advertisements