JavaScript replace()
The replace()
method is a built-in JavaScript function used to search for a specified string or a regular expression pattern and replace the matched occurrences with a new string. The original string remains unchanged, and a new string is returned by the method.
Syntax
string.replace(searchValue, replaceValue)
string.replace(regexp, replaceValue)
- string: Required. The original string where the replacement should take place.
- searchValue: Required. A string to be searched and replaced.
- regexp: Required. A regular expression pattern to be searched and replaced.
- replaceValue: Required. A string to replace the found searchValue or regexp.
Example
let str = "The quick brown fox jumps over the lazy dog.";
let newStr = str.replace('fox', 'cat');
console.log(newStr); // The quick brown cat jumps over the lazy dog.
let regex = /quick|lazy/gi;
newStr = str.replace(regex, 'slow');
console.log(newStr); // The slow brown fox jumps over the slow dog.
Output
The quick brown cat jumps over the lazy dog.
The slow brown fox jumps over the slow dog.