Reversing the words within keeping their order the same JavaScript

In JavaScript, we can reverse each word in a string while maintaining their original positions. This means "Hello World" becomes "olleH dlroW" - each word is reversed individually, but their order remains unchanged.

Understanding the Problem

We need a function that takes a string and returns a new string where each word is reversed, but the word positions stay the same. For example:

  • Input: "Hello World"
  • Output: "olleH dlroW"

The word order is preserved, but each word's characters are reversed.

Method 1: Using Built-in Methods (Recommended)

The most efficient approach uses JavaScript's built-in string methods:

function reverseWords(str) {
   return str.split(' ').map(word => word.split('').reverse().join('')).join(' ');
}

console.log(reverseWords('hello tutorials point'));
console.log(reverseWords('this is a code'));
console.log(reverseWords('JavaScript programming'));
olleh slairotut tniop
siht si a edoc
tpircSavaJ gnimmargorP

How It Works

  1. split(' ') - Splits string into array of words
  2. map() - Transforms each word
  3. word.split('') - Splits word into character array
  4. reverse() - Reverses the character array
  5. join('') - Joins characters back into a word
  6. join(' ') - Joins all words with spaces

Method 2: Using For Loops

A traditional approach using loops for educational purposes:

function reverseWordsManual(str) {
   let words = [];
   let word = '';
   
   // Extract words
   for (let i = 0; i = 0; j--) {
         reversedWord += words[i][j];
      }
      result.push(reversedWord);
   }
   
   return result.join(' ');
}

console.log(reverseWordsManual('hello world'));
console.log(reverseWordsManual('coding challenge'));
olleh dlrow
gnidoc egnellahc

Handling Edge Cases

Both methods handle multiple spaces correctly:

function reverseWordsSafe(str) {
   return str.split(' ').map(word => word.split('').reverse().join('')).join(' ');
}

console.log(reverseWordsSafe('  multiple   spaces  '));
console.log(reverseWordsSafe(''));
console.log(reverseWordsSafe('single'));
  elpitlum   secaps  

elgnis

Comparison

Method Code Length Readability Performance
Built-in Methods 1 line High Optimized
Manual Loops ~20 lines Medium Slower

Time Complexity

Both approaches have O(n×m) complexity, where n is the number of words and m is the average word length. The built-in method is more optimized and concise.

Conclusion

Use the built-in methods approach for cleaner, more maintainable code. The manual loop method helps understand the underlying logic but is unnecessarily verbose for production use.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements