The Wayback Machine - https://web.archive.org/web/20240623182216/https://www.geeksforgeeks.org/javascript-replace-multiple-strings-with-multiple-other-strings/
Open In App

Replace multiple strings with multiple other strings in JavaScript

Last Updated : 30 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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. 

Syntax: 

string.replace(searchVal, newvalue);

Example: This example uses the RegExp to replace the strings according to the object using the replace() method.

Javascript
let str = "I have a Lenovo Laptop, a Honor Phone, and a Samsung Tab.";
let Obj = {
    Lenovo: "Dell",
    Honor: "OnePlus",
    Samsung: "Lenovo"
};

function GFG_Fun() {
    console.log(str.replace(/Lenovo|Honor|Samsung/gi, function (matched) {
        return Obj[matched];
    }));
}
GFG_Fun()

Output
I have a Dell Laptop, a OnePlus Phone, and a Lenovo Tab.

Using the JavaScript str.replaceAll() method

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

Example: This example shows the implementation of the above-explained appraoch.

Javascript
const str = 'who.where_when-how';
const result = str
    .replaceAll('.', '?')
    .replaceAll('_', '?')
    .replaceAll('-', '?');

console.log(result);

Output
who?where?when?how

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.

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

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.

Example: In this example, we will replace multiple substrings using split() and join() methods.

JavaScript
let str = "I have a Lenovo Laptop, a Honor Phone, and a Samsung Tab.";
let replacements = {
    "Lenovo": "Dell",
    "Honor": "OnePlus",
    "Samsung": "Lenovo"
};

function replaceMultiple(str, replacements) {
    for (let [oldStr, newStr] of Object.entries(replacements)) {
        str = str.split(oldStr).join(newStr);
    }
    return str;
}

console.log(replaceMultiple(str, replacements));

Output
I have a Dell Laptop, a OnePlus Phone, and a Lenovo Tab.





Similar Reads

How to replace lowercase letters with an other character in JavaScript ?
Given a string and the task is to replace all lowercase letters from a string with the other characters in JavaScript. There are some approaches to replace the character that are described below: JavaScript replace() Method: This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced define
2 min read
How to replace the names of multiple object keys with the values provided using JavaScript ?
The following approach covers how to replace the names of multiple object keys with the values provided by the user using JavaScript. Problem Statement: You are given an object which contains different key-value pairs in which key symbolizes the property and value itself is known as the property value, and you need to change one or more key's origi
4 min read
Replace Multiple Words with K in JavaScript
Sometimes, while working with Javascript strings, we may face a problem in which we have to perform a replacement of multiple words with a single word. This can have applications in many domains like day-day programming and school programming. These are the following approaches:Table of Content Using join() and split() methodsUsing Regex and join()
5 min read
How to replace multiple spaces with single space in JavaScript ?
In this article, we will see how to replace multiple spaces with a single space in JavaScript. We will have a string having multiple spaces and we need to remove those extra spaces. There are two methods to replace multiple spaces with a single space in JavaScript: Table of Content Method 1: Using replace() MethodMethod 2: Using trim(), split(), an
3 min read
JavaScript Program to Replace Multiple Characters in a String
We are going to learn how we can replace Multiple Characters in a String. We have to replace multiple characters in a string using the inbuilt function or any other method. Table of Content Using replace() methodUsing replaceAll() methodUsing split() and join()Using regular expression Using reduce() Using Map for ReplacementUsing Object for Charact
5 min read
Javascript Program for Pairs such that one is a power multiple of other
You are given an array A[] of n-elements and a positive integer k (k > 1). Now you have find the number of pairs Ai, Aj such that Ai = Aj*(kx) where x is an integer. Note: (Ai, Aj) and (Aj, Ai) must be count once.Examples : Input : A[] = {3, 6, 4, 2}, k = 2 Output : 2 Explanation : We have only two pairs (4, 2) and (3, 6) Input : A[] = {2, 2, 2}
3 min read
How to replace a portion of strings with another value in JavaScript ?
In JavaScript, replacing a portion of strings with another value involves using the `replace()` method or regular expressions. This process is essential for text manipulation tasks like formatting, sanitization, or dynamic content generation in web development and data processing applications. We can replace a portion of a string in multiple ways.
3 min read
Javascript Program to Check if strings are rotations of each other or not | Set 2
Given two strings s1 and s2, check whether s2 is a rotation of s1. Examples:  Input : ABACD, CDABA Output : True Input : GEEKS, EKSGE Output : True We have discussed an approach in earlier post which handles substring match as a pattern. In this post, we will be going to use KMP algorithm's lps (longest proper prefix which is also suffix) construct
2 min read
Javascript Program To Check Whether Two Strings Are Anagram Of Each Other
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. We strongly recommend that you click here and practice it, before moving on to t
7 min read
Check if two strings are permutation of each other in JavaScript
In this approach, we are going to discuss how we can check if two strings are permutations of each other or not using JavaScript language. If two strings have the same number of characters rather than having the same position or not it will be a permutation. Example: Input: "pqrs" , "rpqs"Output: TrueExplanation: Both strings have a same number of
4 min read
three90RightbarBannerImg