The String object's replace() method

Last updated: February 23, 2025

The String object's replace() method returns a new string with one or all matches of a pattern replaced by a replacement string.

Syntax

string.replace(searchValue, replaceValue)

Parameters

searchValue:

  • Can be a string or a Regular Expression (RegExp) object

  • If string, only the first occurrence is replaced

  • If RegExp with global flag ('g'), all occurrences are replaced

replaceValue:

  • Can be a string or a function

  • String can contain special replacement patterns ($&, $`, $', $n)

  • Function is called for each match and its return value is used as replacement

Return value

The replace() method returns a new string with the replacements made. The original string remains unchanged.

Examples

Example 1: Basic string replacement

In the code below, the function replaceEx1() demonstrates basic string replacement operations.

function replaceEx1() {
  let str = "Hello World! Hello Apps Script!";
  
  // Replace first occurrence of 'Hello'
  Logger.log(str.replace("Hello", "Hi"));
  
  // Use RegExp with global flag to replace all occurrences
  Logger.log(str.replace(/Hello/g, "Hi"));

  // Use replaceAll() to replace all occurrences
  Logger.log(str.replaceAll("Hello", "Hi"));
  
  // Case-sensitive by default
  Logger.log(str.replace("hello", "Hi")); // No replacement
  
  // Case-insensitive using RegExp
  Logger.log(str.replace(/hello/gi, "Hi"));
}

Output

Hi World! Hello Apps Script!

Hi World! Hi Apps Script!

Hi World! Hi Apps Script!

Hello World! Hello Apps Script!

Hi World! Hi Apps Script!

Example 2: Using replacement patterns

In the code below, the function replaceEx2() shows how to use special replacement patterns.

function replaceEx2() {
  let str = "John Smith";
  
  // Swap first and last name
  Logger.log(str.replace(/(\w+)\s(\w+)/, "$2, $1"));
  
  let date = "2024-02-23";
  
  // Convert date format from YYYY-MM-DD to MM/DD/YYYY
  Logger.log(date.replace(/(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1"));
  
  // Using $& to reference the matched string
  Logger.log("price".replace(/price/, "$& = $25.00"));
}

Output

Smith, John

02/23/2024

price = $25.00

Example 3: Using a replacement function

In the code below, the function replaceEx3() demonstrates using a function as the replacement value.

function replaceEx3() {
  let str = "cat Dog bird DOG fish CAT";
  
  // Convert animal names to title case
  let result = str.replace(/cat|dog|bird|fish/gi, function(match) {
    return match.charAt(0).toUpperCase() + 
           match.slice(1).toLowerCase();
  });
  
  Logger.log(result);
  
  // Add dollar signs to numbers
  let prices = "Items cost: 5, 10, 15";
  let withDollars = prices.replace(/\d+/g, function(match) {
    return '$' + match;
  });
  
  Logger.log(withDollars);
}

Output

Cat Dog Bird DOG Fish Cat

Items cost: $5, $10, $15

Example 4: Demonstrating immutability

In the code below, the function replaceEx4() shows that replace() returns a new string without modifying the original.

function replaceEx4() {
  let originalStr = "Hello World!";
  
  // Create new string with replacement
  let newStr = originalStr.replace("Hello", "Hi");
  
  // Show that original string is unchanged
  Logger.log("Original string: " + originalStr);
  Logger.log("New string: " + newStr);
  
  // Make another replacement on the new string
  let finalStr = newStr.replace("World", "Apps Script");
  Logger.log("Final string: " + finalStr);
  Logger.log("Original string still unchanged: " + originalStr);
}

Output

Original string: Hello World!

New string: Hi World!

Final string: Hi Apps Script!

Original string still unchanged: Hello World!

Common Use Cases

The replace() method can handle many common text manipulation tasks in Apps Script. Here are some typical scenarios where you might use it:

  • Text formatting and cleaning: Remove unwanted characters, extra spaces, or normalize text formatting. For example, removing multiple spaces or special characters from user input.

  • Date format conversion: Transform dates between different formats, such as changing from YYYY-MM-DD to MM/DD/YYYY or converting between American and European date formats.

  • Name formatting: Standardize name formats by rearranging or reformatting names, such as changing "Smith, John" to "John Smith" or ensuring consistent capitalization.

  • URL manipulation: Clean up or modify URLs by replacing invalid characters, adding or removing parameters, or transforming between different URL formats.

  • Simple template replacement: Fill in template strings with dynamic values, like replacing placeholders in an email template with actual user data.

  • Case normalization: Standardize text case across strings, such as ensuring all product names are in Title Case or converting user input to a consistent format.

Conclusion

In this tutorial, you learned how to use the replace() method to perform string replacements in Apps Script. The method is versatile, supporting both simple string replacements and complex pattern matching with regular expressions. Remember that replace() always returns a new string and doesn't modify the original string. For more complex string manipulations, consider using regular expressions with appropriate flags.

Sign up to be notified when I publish new content

By signing up you agree to the Privacy Policy & Terms.