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:
Methods to Replace Multiple Strings with Multiple Other Strings:
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.
In this example, we will see the use of the JavaScript str.replaceAll() method for replacing multiple strings.
Javascript
const str = 'who.where_when-how' ;
const result = str
.replaceAll( '.' , '?' )
.replaceAll( '_' , '?' )
.replaceAll( '-' , '?' );
console.log(result);
|
Output
who?where?when?how
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
20 Jul, 2023
Like Article
Save Article