Swapping adjacent words of a String in JavaScript

In JavaScript, swapping adjacent words in a string means exchanging pairs of words - the first word with the second, the third with the fourth, and so on. If there's an odd number of words, the last word remains in its position.

Example

Here's how to swap adjacent words using the reduce method:

const str = "This is a sample string only";

const replaceWords = str => {
    return str.split(" ").reduce((acc, val, ind, arr) => {
        if(ind % 2 === 1){
            return acc;
        }
        acc += ((arr[ind+1] || "") + " " + val + " ");
        return acc;
    }, "");
};

console.log(replaceWords(str));
is This sample a only string 

Alternative Method: Using a Simple Loop

A more readable approach uses a for loop to process word pairs:

const str = "This is a sample string only";

const swapAdjacentWords = str => {
    const words = str.split(" ");
    const result = [];
    
    for(let i = 0; i < words.length; i += 2) {
        if(i + 1 < words.length) {
            // Swap adjacent pair
            result.push(words[i + 1]);
            result.push(words[i]);
        } else {
            // Odd word at the end
            result.push(words[i]);
        }
    }
    
    return result.join(" ");
};

console.log(swapAdjacentWords(str));
is This sample a only string

How It Works

The algorithm follows these steps:

  1. Split the string into an array of words using split(" ")
  2. Process words in pairs (indices 0-1, 2-3, 4-5, etc.)
  3. For each pair, add the second word first, then the first word
  4. If there's an unpaired word at the end, add it as-is
  5. Join the result array back into a string

Edge Cases

Testing with different input scenarios:

// Single word
console.log(swapAdjacentWords("Hello"));

// Two words
console.log(swapAdjacentWords("Hello World"));

// Empty string
console.log(swapAdjacentWords(""));

// Extra spaces
console.log(swapAdjacentWords("  Hello   World  Test  "));
Hello
World Hello

  World   Hello  Test  

Conclusion

Swapping adjacent words can be accomplished using either array reduce or a simple loop. The loop method is more readable and handles edge cases more predictably than the reduce approach.

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

556 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements