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

Updated on: 14-Oct-2020

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements