Replacing a piece of text or all occurrences of a text in JavaScript is a common task that most developers come across. Luckily, JavaScript provides an in-built function called replace() that does the job quite well.

The replace() function in JavaScript allows you to search for a piece of text in a string variable and have it replaced with a specific value. With this function, you can either replace the first instance of value or replace all occurrences of it.

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.

stringVariable.replace(searchString, newString)

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().

Replace the First Occurrence of a String:

const intro = "Welcome to CodeZen!";
const newIntro = intro.replace("CodeZen", "JavaScript");



Welcome to JavaScript!

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");



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 i modifier:

const str = "CATs are my favorite animal and I wish I had a Cat as my pet.";
const newStr = str.replace(/cat/gi, "Dog");