Reverse each word
JavaScript
Easy
Objective
Write a function that reverses each word in a string
Requirements
The function should be called
reverseEachWord
It should take a single string as an argument
It should return the string with each word reversed
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