Swapping adjacent words of a String in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 14-Oct-2020 07:56:02
Advertisements