replace, replaceAll

Replacing string content.

Examples

Basic Replace

Replacing the first occurrence of a string.

let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "Example");
console.log(newText);

Case Insensitive Replace

Using a regular expression with 'i' flag.

let text = "Please visit Microsoft!";
let newText = text.replace(/MICROSOFT/i, "Example");
console.log(newText);

Using replaceAll()

Replacing all occurrences of a string.

let text = "I love cats. Cats are very easy to love. Cats are very popular."
text = text.replaceAll("Cats", "Dogs");
text = text.replaceAll("cats", "dogs");
console.log(text);

Test Your Knowledge

JavaScript Quiz

No quiz available for this topic yet.