Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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:
- Split the string into an array of words using
split(" ") - Process words in pairs (indices 0-1, 2-3, 4-5, etc.)
- For each pair, add the second word first, then the first word
- If there's an unpaired word at the end, add it as-is
- 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.
Advertisements
