How to use Array.reduce() method In Javascript
Using Array.reduce() with replaceAll() method, the approach iterates over an array of replacement pairs, applying each replacement to the string sequentially. It uses regular expressions to globally replace occurrences of each old string with its corresponding new string.
Example: In this example we replaces multiple characters in a string with ‘?’ using Array.reduce() and replaceAll().
const str = 'who.where_when-how';
const replacements = [
['.', '?'],
['_', '?'],
['-', '?']
];
const result = replacements.reduce((acc, [oldStr, newStr]) => {
return acc.replaceAll(oldStr, newStr);
}, str);
console.log(result);
Output
who?where?when?how
Replace multiple strings with multiple other strings in JavaScript
In this article, we are given a Sentence having multiple strings. The task is to replace multiple strings with new strings simultaneously instead of doing it one by one, using JavaScript.
Below are a few methods to understand:
Table of Content
- Using JavaScript replace() method
- Using the JavaScript str.replaceAll() method
- Using Array.reduce() method: