EasyUiPath

Reverse Words in a String

Prompt

Write a function reverseWords that takes a string and returns a new string where each word is reversed individually, but the order of the words stays the same.

reverseWords('Hello World'); // "olleH dlroW"

Playground

Hint 1

Start by splitting the string into an array of words using split(' '). Once you have the words separately, you can work on reversing each one individually.

Hint 2

JavaScript strings don't have a .reverse() method, but arrays do. You can convert a word to an array of characters with split(''), reverse that array, and convert it back to a string with join('').

Solution

Explanation

The question sounds tricky at first, but once you see the approach, it's really just three steps chained together.

The key insight is that JavaScript strings don't have a .reverse() method. Arrays do. So to reverse a word, you need to convert it to an array first, reverse the array, and convert it back to a string. That's the split('').reverse().join('') chain you see everywhere in JavaScript string manipulation.

Let's trace what happens to the word "Hello":

'Hello'
.split('') // ['H', 'e', 'l', 'l', 'o']
.reverse() // ['o', 'l', 'l', 'e', 'H']
.join(''); // 'olleH'

split('') breaks the string into individual characters. .reverse() flips the array. .join('') glues the characters back into a string. Three steps, and the word is reversed.

Now we just need to do this for every word in the sentence. That's where split(' ') and map come in:

'Hello World'.split(' '); // ['Hello', 'World']

This gives us an array of words. We .map() over each word and apply the reversal, then .join(' ') the reversed words back into a sentence with spaces between them.

The whole thing reads as: split into words, reverse each word, join back with spaces.

str
.split(' ')
.map((word) => word.split('').reverse().join(''))
.join(' ');

Notice that the order of the words doesn't change. "Hello" is still first and "World" is still second. We're only reversing the characters within each word.

Also, palindromes like "madam" and "racecar" come out the same after reversal. That's a fun edge case to test with.