Reverse each word

JavaScript
Easy

Objective

Write a function that reverses each word in a string

Requirements

  1. The function should be called reverseEachWord

  2. It should take a single string as an argument

  3. It should return the string with each word reversed

    1. The words should remain in their original order

Check your solution

Tests

Function name is reverseEachWord
reverseEachWord("Hello, World!")Expected:",olleH !dlroW"
reverseEachWord("Lorem ipsum dolor sit amet")Expected:"meroL muspi rolod tis tema"

Solution

Here's how I would approach this, but keep in mind there might be other ways to solve this problem.

function reverseEachWord(string) { const words = string.split(' '); const reversedWords = words.map((word) => { return word.split('').reverse().join(''); }); return reversedWords.join(' '); }
Click to reveal