JavaScript replace/regex
Categories:
Mastering JavaScript replace()
with Regular Expressions

Unlock the full potential of JavaScript's replace()
method by combining it with regular expressions for powerful string manipulation, pattern matching, and dynamic content transformation.
The replace()
method in JavaScript is a fundamental tool for modifying strings. While it can perform simple substring replacements, its true power emerges when paired with regular expressions (regex). This combination allows for complex pattern matching, global replacements, and dynamic content generation, making it indispensable for tasks like data cleaning, formatting, and text processing. This article will guide you through the various ways to leverage replace()
with regex, from basic usage to advanced techniques.
Understanding String.prototype.replace()
The replace()
method returns a new string with some or all matches of a pattern
replaced by a replacement
. The original string remains unchanged. Its basic syntax is str.replace(pattern, replacement)
.
When the pattern
is a string, replace()
will only replace the first occurrence of that string. To replace all occurrences, you must use a regular expression with the global (g
) flag.
// Replacing a simple string (only the first occurrence)
const text = "Hello world, hello universe!";
const newText = text.replace("hello", "hi");
console.log(newText); // Output: "Hello world, hi universe!"
// Using regex with the 'g' flag for global replacement
const newTextGlobal = text.replace(/hello/g, "hi");
console.log(newTextGlobal); // Output: "hi world, hi universe!"
Basic usage of replace()
with string and regex patterns.
The Power of Regular Expressions in replace()
Regular expressions provide a concise and flexible means for matching strings of text, such as particular characters, words, or patterns of characters. When used with replace()
, they allow you to define sophisticated search criteria and perform replacements based on those criteria.
flowchart TD A[Start `replace()`] --> B{Pattern Type?} B -->|String| C[Replace first match] B -->|Regex| D{Global Flag 'g'?} D -->|No| E[Replace first match] D -->|Yes| F[Replace all matches] C --> G[Return new string] E --> G F --> G
Decision flow for replace()
behavior based on pattern type and global flag.
Using Capture Groups for Dynamic Replacements
Capture groups in regular expressions allow you to extract specific parts of a matched string. These captured parts can then be referenced in the replacement string using $1
, $2
, etc., corresponding to the order of the capture groups. This is incredibly powerful for reformatting data.
// Reordering names from "Last, First" to "First Last"
const name = "Doe, John";
const formattedName = name.replace(/(\w+), (\w+)/, "$2 $1");
console.log(formattedName); // Output: "John Doe"
// Extracting and reformatting a date string
const date = "2023-10-26";
const formattedDate = date.replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1");
console.log(formattedDate); // Output: "26/10/2023"
Examples of using capture groups ($n
) for reordering and reformatting strings.
$0
(or $&
) refers to the entire matched string, not the first capture group. $1
refers to the content of the first capturing parenthesis, $2
to the second, and so on.Replacement with a Function
For even more complex and dynamic replacements, you can provide a function as the replacement
argument. This function will be invoked for each match, and its return value will be used as the replacement string. The function receives several arguments:
match
: The entire matched substring.p1, p2, ...
: The captured groups (if any).offset
: The offset of the matched substring within the original string.string
: The original string being processed.
// Capitalizing the first letter of each word
const sentence = "hello world from javascript";
const capitalizedSentence = sentence.replace(/\b\w/g, (char) => char.toUpperCase());
console.log(capitalizedSentence); // Output: "Hello World From Javascript"
// Replacing numbers with their squared values
const numbers = "The numbers are 2, 5, and 10.";
const squaredNumbers = numbers.replace(/\d+/g, (match) => parseInt(match) * parseInt(match));
console.log(squaredNumbers); // Output: "The numbers are 4, 25, and 100."
Using a replacement function for dynamic string transformations.
Common Regex Flags for replace()
Several flags can modify the behavior of regular expressions in JavaScript. The most commonly used with replace()
are:
g
(global): Performs a global match (finds all matches rather than stopping after the first).i
(insensitive): Performs case-insensitive matching.m
(multiline): Treats beginning and end anchors (^
and$
) as matching the start/end of each line, not just the start/end of the whole string.
// Case-insensitive global replacement
const mixedCase = "Apple, apple, APPLE!";
const newMixedCase = mixedCase.replace(/apple/gi, "orange");
console.log(newMixedCase); // Output: "Orange, orange, ORANGE!"
// Multiline matching example
const multilineText = "Line 1\nLine 2\nLine 3";
const startsWithLine = multilineText.replace(/^Line/gm, "Start");
console.log(startsWithLine);
/* Output:
Start 1
Start 2
Start 3
*/
Demonstrating the i
(case-insensitive) and m
(multiline) flags.
1. Identify the Pattern
Determine what specific text or pattern you need to find within your string. This could be a fixed string, a set of characters, or a more complex structure like an email address or date format.
2. Construct the Regular Expression
Translate your identified pattern into a regular expression. Use appropriate special characters, quantifiers, and character classes. If you need to replace all occurrences, remember to include the g
flag (e.g., /pattern/g
). Add other flags like i
for case-insensitivity if needed.
3. Define the Replacement Logic
Decide what the matched pattern should be replaced with. This can be a simple string, or if you need dynamic content or to reorder parts of the match, use a replacement function or capture group references ($1
, $2
, etc.).
4. Apply replace()
Execute the str.replace(regex, replacement)
method. Test thoroughly with various inputs to ensure it behaves as expected, especially for edge cases.