JavaScript replace() method


The replace() method in JavaScript is used to search for a specified substring or pattern in a string and replace it with a new substring. This method is particularly useful for string manipulation, such as modifying text, sanitizing inputs, or formatting data.

Syntax:

string.replace(searchValue, newValue)
  • searchValue: This can be either a string or a regular expression. It specifies the substring or pattern to search for in the original string.
  • newValue: This is the string that will replace the matched substring(s). It can also be a function that returns the replacement string.

Return Value:

  • Returns a new string with some or all matches of searchValue replaced by newValue. The original string remains unchanged.

Example 1: Basic String Replacement

let str = "Hello World!"; let newStr = str.replace("World", "JavaScript"); console.log(newStr); // "Hello JavaScript!"

In this example, the substring "World" is replaced with "JavaScript".

Example 2: Case Sensitivity

The replace() method is case-sensitive, meaning it will only replace substrings that match the exact case.

let str = "Hello World!"; let newStr = str.replace("world", "JavaScript"); console.log(newStr); // "Hello World!" (no change)

Example 3: Using Regular Expressions

You can use regular expressions with replace() for more complex search patterns.

let str = "The rain in Spain stays mainly in the plain."; let newStr = str.replace(/ain/g, "ane"); console.log(newStr); // "The rane in Spane stane mainly in the plane."

In this example, the regular expression /ain/g is used to replace all occurrences of "ain" with "ane". The g flag indicates a global search, meaning all matches will be replaced.

Example 4: Using a Function for Replacement

You can also pass a function as the newValue argument. This function will be called for each match, allowing for dynamic replacements based on the match.

let str = "The price is $5 and $10."; let newStr = str.replace(/\$(\d+)/g, (match, p1) => { return `$${p1 * 2}`; // Double the price }); console.log(newStr); // "The price is $10 and $20."

In this example, the function doubles each price found in the string.

Example 5: Replacing All Occurrences

To replace all occurrences of a substring, you can either use a regular expression with the g flag or convert the substring to a regular expression.

let str = "Banana is my favorite fruit. Banana is yellow."; let newStr = str.replace(/Banana/g, "Apple"); console.log(newStr); // "Apple is my favorite fruit. Apple is yellow."

Example 6: Using Special Replacement Patterns

The newValue string can also contain special replacement patterns like $&, $1, $2, etc., which represent the matched substring and capture groups, respectively.

let str = "John Doe"; let newStr = str.replace(/(\w+)\s(\w+)/, "$2, $1"); console.log(newStr); // "Doe, John"

In this example, the first and last names are swapped using capture groups.

Summary:

  • The replace() method in JavaScript is used to search for and replace substrings in a string.
  • It can take a string or a regular expression as the search value and a string or function as the new value.
  • The method returns a new string, leaving the original string unchanged.
  • It is case-sensitive and can handle both single and multiple occurrences based on whether a regular expression is used.
  • It supports dynamic replacements through a callback function and allows the use of special replacement patterns.