The function takes two parameters, the first is the value which you wish to replace and the second parameter is the new value with which it has to be replaced.
The return value of this function is a new string where the specified text has been replaced by a new text. Here are some examples to demonstrate the use of
Replace the First Occurrence of a String:
Replace All Occurences of a String with Regex
The replace() function replaces the first instance of a given text. If you wish to replace all instances of a text, then you have to use regex.
const str = "cats are my favorite animal and I wish I had a cat as my pet."; const newStr = str.replace(/cat/g, "dog"); console.log(newStr);
dogs are my favorite animal and I wish I had a dog as my pet.
To perform a case-insensitive replacement, you have to use the regex
const str = "CATs are my favorite animal and I wish I had a Cat as my pet."; const newStr = str.replace(/cat/gi, "Dog"); console.log(newStr);