regex string replace

Learn regex string replace with practical examples, diagrams, and best practices. Covers javascript, regex, string development techniques with visual explanations.

Mastering Regex String Replacement in JavaScript

Hero image for regex string replace

Learn how to effectively use regular expressions for powerful string replacement operations in JavaScript, covering single, global, and dynamic replacements.

String replacement is a fundamental operation in programming, and when combined with the power of regular expressions (regex), it becomes an incredibly versatile tool for data manipulation, parsing, and formatting. In JavaScript, the String.prototype.replace() method is your primary interface for performing these operations. This article will guide you through the various ways to use regex with replace(), from simple substitutions to complex dynamic replacements using callback functions.

Basic String.prototype.replace() with Regex

The replace() method can take either a string or a regular expression as its first argument (the pattern). When a regex is provided, it unlocks powerful pattern matching capabilities. By default, if the regex does not include the global flag (g), replace() will only replace the first occurrence of the matched pattern.

const text = "Hello world, hello JavaScript!";

// Replace only the first occurrence of 'hello' (case-insensitive)
const result1 = text.replace(/hello/i, "Hi");
console.log(result1); // Output: "Hi world, hello JavaScript!"

// Replace a specific word
const result2 = text.replace(/world/, "universe");
console.log(result2); // Output: "Hello universe, hello JavaScript!"

Basic regex replacement without the global flag.

Global Replacement with the 'g' Flag

To replace all occurrences of a pattern within a string, you must include the global flag (g) in your regular expression. This is one of the most common use cases for regex replacement, allowing you to standardize text, remove unwanted characters, or format data consistently across an entire string.

const sentence = "The quick brown fox jumps over the lazy dog. The fox is quick.";

// Replace all occurrences of 'fox' with 'cat'
const globalReplace = sentence.replace(/fox/g, "cat");
console.log(globalReplace); // Output: "The quick brown cat jumps over the lazy dog. The cat is quick."

// Replace all whitespace with a single space
const cleanWhitespace = "  Hello   world!  ".replace(/\s+/g, " ").trim();
console.log(cleanWhitespace); // Output: "Hello world!"

Using the global flag (g) for multiple replacements.

flowchart TD
    A[Input String] --> B{Regex Pattern?}
    B -- No --> C[String Literal Match]
    B -- Yes --> D{Global Flag 'g'?}
    D -- No --> E[Replace First Match]
    D -- Yes --> F[Replace All Matches]
    C --> G[Output String]
    E --> G
    F --> G

Decision flow for String.prototype.replace() with regex.

Dynamic Replacement with a Callback Function

The replace() method's second argument can also be a function. This callback function is executed for each match found by the regex, and its return value is used as the replacement string. This provides immense flexibility, allowing you to perform complex transformations based on the matched content, captured groups, and their positions.

The callback function receives several arguments:

  1. match: The entire matched substring.
  2. p1, p2, ...: Captured groups from the regex (if any).
  3. offset: The offset (position) of the matched substring within the original string.
  4. string: The original string being processed.
const productCode = "item-123-ABC-456";

// Convert all uppercase letters to lowercase and prepend with underscore
const formattedCode = productCode.replace(/[A-Z]+/g, (match) => {
  return `_${match.toLowerCase()}`;
});
console.log(formattedCode); // Output: "item-123-_abc-456"

const priceList = "Price: $10.50, Cost: $5.25";

// Double all dollar amounts
const doubledPrices = priceList.replace(/\$(\d+\.\d{2})/g, (match, p1) => {
  const originalPrice = parseFloat(p1);
  const doubledPrice = (originalPrice * 2).toFixed(2);
  return `\$${doubledPrice}`;
});
console.log(doubledPrices); // Output: "Price: $21.00, Cost: $10.50"

Using a callback function for dynamic regex replacement.

Using Captured Groups in Replacement Strings

Regular expressions allow you to define 'captured groups' using parentheses (). These groups can then be referenced in the replacement string using $1, $2, etc., corresponding to the order of the capturing groups. This is incredibly useful for reordering parts of a string or inserting matched content into a new structure.

const dateString = "2023-10-26";

// Reformat date from YYYY-MM-DD to MM/DD/YYYY
const reformattedDate = dateString.replace(/(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1");
console.log(reformattedDate); // Output: "10/26/2023"

const name = "Doe, John";

// Reformat name from 'Last, First' to 'First Last'
const reformattedName = name.replace(/(\w+), (\w+)/, "$2 $1");
console.log(reformattedName); // Output: "John Doe"

Referencing captured groups ($1, $2) in the replacement string.