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