Replacing Substrings with replace
You'll learn how to swap out the first piece of matching text in a string using the replace method.
What Does replace Do?
The replace method searches a string for a pattern (either a substring or a regular expression) and replaces the first occurrence with something new. Think of it like using "Find & Replace" in a word processor, but by default it only changes the first match it finds.
The original string stays unchanged (remember, strings are immutable), and replace returns a new string with the substitution made.
Basic Syntax with Strings
let sentence = "I love cats and cats are great";
let newSentence = sentence.replace("cats", "dogs");
console.log(newSentence); // "I love dogs and cats are great"
console.log(sentence); // "I love cats and cats are great" (unchanged)
Notice only the first "cats" became "dogs"—the second one stayed the same.
Using Regular Expressions for More Control
You can pass a regular expression instead of a plain string to find patterns. To replace all occurrences, use a global regex with the g flag:
let sentence = "I love cats and cats are great";
let allReplaced = sentence.replace(/cats/g, "dogs");
console.log(allReplaced); // "I love dogs and dogs are great"
You can also make replacements case-insensitive using the i flag:
let text = "Hello hello HELLO";
let replaced = text.replace(/hello/i, "Hi");
console.log(replaced); // "Hi hello HELLO" (only first match, case-insensitive)
Key Takeaway: Use replace to substitute the first occurrence of a substring or pattern; pass a string for literal matches or a regular expression (with flags like g) for more powerful pattern-based replacements.