
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
Replace Words of a String in 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
Advertisements