What is the string replace() method in JavaScript?
The replace() method in JavaScript is used to replace a substring or regular expression of a string with another substring or regular expression.
Syntax
The replace() method can be declared as shown in the code snippet below:
string.replace(oldValue, newValue)
Parameters
-
oldValue: The substring or regular expression of the string that will be replaced withnewValue. -
newValue: The substring or regular expression that will replaceoldValuein the string.
Return value
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.
Browser compatibility
The following browsers support the replace() method:
- Chrome 1
- Edge 12
- Firefox 1
- Internet Explorer 5.5
- Opera 4
- Safari 1
Code
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);
Explanation
-
We declare a string
strin line 1. -
We use the
replace()method in line 4 to replace the substring"eg."with the substring"example"instr. -
The changes are made and returned in the string
str2, andstrremains unchanged.