Search & Replace

In JavaScript, searching and replacing text within strings is commonly done using the String.prototype.replace() method. It allows you to find a pattern in a string and replace it with a new substring.

Illustration of Search & Replace
Illustration of Search & Replace

💡 Important:

The replace() method does not change the original string; it returns a new string with the replacements.

Basic Syntax

str.replace(searchValue, newValue)

  • searchValue: A substring or a regular expression to find.
  • newValue: The replacement string or a function to generate it.

📌 Deep Dive: Simple Replace

JAVASCRIPT
const greeting = "Hello World";
const newGreeting = greeting.replace("World", "JavaScript");
console.log(newGreeting);
Output
Hello JavaScript

Replacing All Occurrences

By default, replace() only replaces the first match. To replace all occurrences, use a global regular expression with the g flag.

📌 Deep Dive: Replace All

JAVASCRIPT
const text = "one fish, two fish, red fish, blue fish";
const result = text.replace(/fish/g, "cat");
console.log(result);
Output
one cat, two cat, red cat, blue cat

⚠️ Case Sensitivity

Regular expressions are case-sensitive by default. Use the i flag for case-insensitive replacements, e.g., /pattern/gi.

Using a Function as Replacement

You can supply a function as the second argument to replace(). This function receives matched substrings and can dynamically determine the replacement.

📌 Deep Dive: Function Replacement

JAVASCRIPT
const prices = "Apples: $5, Oranges: $7";
const updatedPrices = prices.replace(/\$(\d+)/g, (match, p1) => {
  return `$${Number(p1) * 2}`;
});
console.log(updatedPrices);
Output
Apples: $10, Oranges: $14
Comparison of Replace Methods
MethodBehavior
replace("a", "b")Replaces first occurrence of "a".
replace(/a/g, "b")Replaces all occurrences of "a".
replace(/a/gi, "b")Replaces all occurrences of "a", case-insensitive.
replace(/a/g, (match) => ...)Replaces all with dynamic replacement via function.

💡 Tips for Effective Search & Replace

  • Use regular expressions for flexible pattern matching.
  • Remember that strings are immutable; replace() returns a new string.
  • Escape special regex characters when searching for literal strings.