How to use reduce() Function In Javascript
In this approach, we split the string into an array of substrings using the split() method, and then we use the reduce() function to concatenate the substrings, inserting the replacement string where the original substring occurs. This method gives us fine control over the replacement process and can be useful for more complex string manipulations.
Example: In this example we splits the str string by the searchString ‘Welcome’, then joins the parts with ‘Hello’ in between, effectively replacing all occurrences, and logs the result.
// Original String
const str = 'Welcome w3wiki, Welcome geeks';
const searchString = "Welcome";
const replacementString = "Hello";
// Replace all occurrences of Welcome with Hello
const newString = str.split(searchString).reduce((acc, current, index, array) => {
return acc + current + (index < array.length - 1 ? replacementString : '');
}, '');
// Display the result
console.log(newString);
Output
Hello w3wiki, Hello geeks
How to replace all occurrences of a string in JavaScript ?
Replacing all occurrences of a string in JavaScript is a common task in text processing. It involves identifying and substituting specific substrings within a larger string. This capability is crucial for tasks such as data cleaning, formatting, and transforming text in various applications.
These are the following methods to replace all occurrences of a string in JavaScript:
Table of Content
- Using string.replace() method
- Using String split() and join() Method
- Using replaceAll() Method
- Using regular expression
- Using reduce() Function