Replace words of a string - JavaScript


We are required to write a JavaScript function that takes in a string and replaces the adjacent words of that string.

For example: If the input string is −

const str = "This is a sample string only";

Then the output should be −

"is This sample a only string"

Let’s write the code for this function −

Example

Following is the code −

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

Following is the output in the console −

is This sample a only string

Updated on: 14-Sep-2020

262 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements