Reverse words

Instructions: Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained. Examples "This is an example!" ==> "sihT si na !elpmaxe" "double spaces" ==> "elbuod secaps" Thoughts: I splut the total string into an array of words of type string. 2.Using map function I take every single word(array element) of the array, split the word in individual letters in an array, reverse this array and join it back into a word, reversed this time. const revrs = arr.map((el) => { const rvrEl = el.split("").reverse().join(""); At the end I join all the words in the array together. Solution: function reverseWords(str) { const arr = str.split(" "); const revrs = arr.map((el) => { const rvrEl = el.split("").reverse().join(""); return rvrEl; }); return revrs.join(" "); } This is a CodeWars Challenge of 7kyu Rank (https://www.codewars.com/kata/5259b20d6021e9e14c0010d4/train/javascript)

Apr 26, 2025 - 05:24
 0
Reverse words

Instructions:
Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained.

Examples
"This is an example!" ==> "sihT si na !elpmaxe"
"double spaces" ==> "elbuod secaps"

Thoughts:

  1. I splut the total string into an array of words of type string. 2.Using map function I take every single word(array element) of the array, split the word in individual letters in an array, reverse this array and join it back into a word, reversed this time. const revrs = arr.map((el) => { const rvrEl = el.split("").reverse().join("");
  2. At the end I join all the words in the array together.

Solution:

function reverseWords(str) {
   const arr = str.split(" ");
  const revrs = arr.map((el) => {
    const rvrEl = el.split("").reverse().join("");
    return rvrEl;
  });
  return revrs.join(" ");
}

This is a CodeWars Challenge of 7kyu Rank (https://www.codewars.com/kata/5259b20d6021e9e14c0010d4/train/javascript)