
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- Replace all occurrence of specific words in a sentence based on an array of words in JavaScript
- Swapping adjacent words of a String in JavaScript
- Reversing words within a string JavaScript
- Finding the number of words in a string JavaScript
- Replace all words with another string with Java Regular Expressions
- Reversing words in a string in JavaScript
- Finding duplicate "words" in a string - JavaScript
- Reversing the order of words of a string in JavaScript
- String function to replace nth occurrence of a character in a string JavaScript
- How to replace all occurrences of a string in JavaScript?
- Reversing the even length words of a string in JavaScript
- Interchanging first letters of words in a string in JavaScript
- Create a polyfill to replace nth occurrence of a string JavaScript
- Reversing words present in a string in JavaScript
- Returning lengthy words from a string using JavaScript

Advertisements