Home >>JavaScript String Methods >JavaScript String replace() Method
JavaScript replace() method is used to replace a specified part of the given input string with a defined value or a regular expression. It returns a new string where the defined values are replaced but it does not change the original given string.
Syntax:
string.replace(searchvalue, newvalue)
Parameter | Description |
---|---|
searchvalue | This is a required parameter. It defines the value, or regular expression, that will be replaced by the new value. |
newvalue | This is a required parameter. It defines he value to replace the search value with. |
Method | Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
replace() | Yes | Yes | Yes | Yes | Yes |
Here is an example of replace() method:
<html> <body> <p>Click the button to see the Output.</p> <p id="demo">Hello!! I am Jerry..</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var str = document.getElementById("demo").innerHTML; var res = str.replace("Jerry", "Abhimanyu"); document.getElementById("demo").innerHTML = res; } </script> </body> </html>
Click the button to see the Output.
Hello!! I am Jerry..
Example 2:
<html> <body> <p>Click the button to see the Output.</p> <p id="demo1">I have a blue car, blue pen, blue jacket and a Blue t-shirt.</p> <button onclick="myFunction1()">Try it</button> <script> function myFunction1() { var str = document.getElementById("demo1").innerHTML; var res = str.replace(/blue/gi, "black"); document.getElementById("demo1").innerHTML = res; } </script> </body> </html>
Click the button to see the Output.
I have a blue car, blue pen, blue jacket and a Blue t-shirt.