The replace()
method in JavaScript is used to replace a substring or regular expression of a string with another substring or regular expression.
The replace()
method can be declared as shown in the code snippet below:
string.replace(oldValue, newValue)
oldValue
: The substring or regular expression of the string that will be replaced with newValue
.
newValue
: The substring or regular expression that will replace oldValue
in the string.
The replace()
method returns the string after oldValue
is replaced with newValue
.
The string itself is not changed. The changes are made in a copy of the string, and that copy is returned.
The following browsers support the replace()
method:
Consider the code snippet below, which demonstrates the use of the replace()
method:
let str = "Hello World! This is replace() eg. code";console.log("str before replace(): " + str);let str2 = str.replace("eg.", "example");console.log("str after replace(): " + str2);
We declare a string str
in line 1.
We use the replace()
method in line 4 to replace the substring "eg."
with the substring "example"
in str
.
The changes are made and returned in the string str2
, and str
remains unchanged.