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().

JavaScript
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:

Similar Reads

Using JavaScript replace() method

This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value....

Using the JavaScript str.replaceAll() method

In this example, we will see the use of the JavaScript str.replaceAll() method for replacing multiple strings....

Using Array.reduce() method:

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....

Using JavaScript String.split() and Array.join() Method

This method involves using split() to break the string at each target substring and then using join() to reassemble the string with the new substring in place of the target substrings....

Contact Us