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:
- split(‘ ‘): The string is split into words based on spaces.
- 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. - 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'
.