DEV Community

Madalina Pastiu
Madalina Pastiu

Posted on

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(" "); } 
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)