How to use replace() method In Javascript
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.
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:
Contact Us