
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements