Reverse Words in a String

EasyUiPath

Prompt

Write a function named reverseWords in JavaScript that takes a string as an argument and returns a new string where each word is reversed, but the order of the words remains the same. A word is defined as a sequence of non-space characters.

Requirements

  • The function should reverse each word in the input string while maintaining word order.
  • Words are separated by one or more spaces.
  • The output string should preserve the original spacing between words.
  • Special characters and numbers within words should also be reversed.

Example

reverseWords("Welcome to UiPath"); // "emocleW ot htaPiU"
reverseWords("Hello World"); // "olleH dlroW"
reverseWords("JavaScript is awesome"); // "tpircSavaJ si emosewa"

Playground

Hint 1

You can split the string into an array of words, then reverse each word individually, and finally join them back together preserving the original spacing.

Solution

Explanation

This problem requires us to reverse each individual word in a string while maintaining the order of words. Here's how the solution works:

First, we split the input string by spaces to get an array of words.

const words = s.split(' ');

This preserves all spaces (including multiple spaces) as empty strings in the array.

Next, we use the map() method to process each word in the array.

const reversedWords = words.map(word => {
return word.split('').reverse().join('');
});

For each word, we:

  • Split it into an array of characters using split('')
  • Reverse the array of characters using reverse()
  • Join the characters back into a string using join('')

Finally, we join the array of reversed words back together with spaces, preserving the original spacing.

return reversedWords.join(' ');

This solution handles spaces correctly, including multiple spaces between words. Empty strings (which represent spaces in the original string) will remain empty after reversing, so the spacing pattern of the original string is preserved.

The time complexity is O(n) where n is the total number of characters in the input string, as we need to process each character once.

00:00