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:
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
<body style= "text-align:center;" id= "body" > <h1 style= "color:green;" >GeeksForGeeks</h1> <h3> JavaScript | Replace multiple strings with multiple other strings. </h3> <p id= "GFG_UP" style= "font-size: 19px; font-weight: bold;" > </p> <button onClick= "GFG_Fun()" > click here </button> <p id= "GFG_DOWN" style= "color: green; font-size: 24px; font-weight: bold;" > </p> <script> var up = document.getElementById( 'GFG_UP' ); var down = document.getElementById( 'GFG_DOWN' ); var str = "I have a Lenovo Laptop, a Honor Phone, and a Samsung Tab." ; var Obj = { Lenovo: "Dell" , Honor: "OnePlus" , Samsung: "Lenovo" }; up.innerHTML = str; function GFG_Fun() { down.innerHTML = str.replace(/Lenovo|Honor|Samsung/gi, function (matched){ return Obj[matched]; }); } </script> </body> |
Output:

Replace multiple strings with multiple other strings
Please Login to comment...