
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Swapping adjacent words of a String in JavaScript
We are required to write a JavaScript function that takes in a string and swaps the adjacent words of that string with one another until the end of that string.
Example
The code for this will be −
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));
Output
The output in the console −
is This sample a only string
- Related Articles
- Counting adjacent pairs of words in JavaScript
- Swapping adjacent binary bits of a decimal to yield another decimal using JavaScript
- Swapping string case using a binary number in JavaScript
- Replace words of a string - JavaScript
- Swapping Characters of a String in Java
- Swapping Characters of a String in C#
- Removing adjacent duplicates from a string in JavaScript
- Reversing words in a string in JavaScript
- Finding the number of words in a string JavaScript
- Finding duplicate "words" in a string - JavaScript
- Reversing the order of words of a string in JavaScript
- Reversing words within a string JavaScript
- Interchanging first letters of words in a string in JavaScript
- Reversing words present in a string in JavaScript
- Reversing the even length words of a string in JavaScript

Advertisements