Logic Thinking

Aug 28, 2024

reverse alternative word of string

function reverseStr(str) {
return str.split(' ').map((word, index) => {
return index % 2 === 1 ? word.split('').reverse().join('') : word;
}).join(' ');
}

const input = 'i am frontend developer';
const result = reverseStr(input);
console.log(result); // Output: "i ma frontend repoleved"

Explanation:

  1. split(‘ ‘): The string is split into words based on spaces.
  2. map((word, index) => { … }): The map function is used to iterate over each word. If the word is at an odd index (index % 2 === 1), it is reversed.
  3. join(‘ ‘): The words are then joined back into a single string, with spaces between them.

Output:

For the input 'i am frontend developer', the output would be 'i ma frontend repoleved'.

--

--

PROFESSOR !!
PROFESSOR !!

Written by PROFESSOR !!

start the journey with me and be a master in js and react to beacome a frontend developer

No responses yet