Regex Tester & DebuggerSpecialized Version
🔍

Regex Replace Tool

Regex replace

//g
Flags:
Examples:

Regex Replace Tool

Perform powerful find and replace operations using regular expressions. Use capture groups to restructure and transform text.

Basic Regex Replace

``javascript // Simple replacement text.replace(/old/g, 'new');

// With regex pattern text.replace(/\d+/g, '#'); // Replace all numbers with #

// Case-insensitive text.replace(/hello/gi, 'hi'); `

Using Capture Groups

SyntaxMeaningExample
$1, $2Captured groupsReplace with group values
$&Entire matchWrap matches
$Before matchInsert text before
$'After matchInsert text after
$$Literal $Escape dollar sign

Regex Replace Examples

``javascript // Swap first and last name "John Smith".replace(/(\w+) (\w+)/, '$2, $1'); // Result: "Smith, John"

// Format phone number "5551234567".replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3'); // Result: "(555) 123-4567"

// Wrap matches in tags "Error: failed".replace(/Error:/g, '$&'); // Result: "Error: failed"

// Remove duplicate words "the the quick".replace(/\b(\w+)\s+\1\b/gi, '$1'); // Result: "the quick"

// Convert date format (MM/DD/YYYY to YYYY-MM-DD) "12/25/2024".replace(/(\d{2})\/(\d{2})\/(\d{4})/, '$3-$1-$2'); // Result: "2024-12-25"

// CamelCase to kebab-case "camelCaseText".replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); // Result: "camel-case-text" `

Replace with Function

`javascript // Dynamic replacement based on match "price: $100".replace(/\$(\d+)/g, (match, amount) => { return '$' + (parseInt(amount) * 1.1).toFixed(2); // Add 10% }); // Result: "price: $110.00"

// Titlecase words "hello world".replace(/\b\w/g, c => c.toUpperCase()); // Result: "Hello World"

// Mask sensitive data "SSN: 123-45-6789".replace(/\d{3}-\d{2}-(?=\d{4})/, 'XXX-XX-'); // Result: "SSN: XXX-XX-6789" `

Common Replacements

TaskPatternReplacement
Trim whitespace^\s+\\s+$''
Collapse spaces\s+' '
Remove HTML tags<[^>]+>''
Escape HTML[&<>"']Function
Normalize newlines\r\n?\\n'\n'`

Frequently Asked Questions

How do I use captured groups in replacement?

Use $1, $2, etc. to reference captured groups. Pattern (\\d{3})-(\\d{4}) with replacement ($1) $2 transforms "555-1234" to "(555) 1234". Groups are numbered left-to-right by their opening parenthesis. Named groups use $<name> syntax.

Why is my replacement only changing the first match?

You need the global flag (g). Without /g, replace() only replaces the first match. Compare: "a a a".replace(/a/, "b") → "b a a" vs "a a a".replace(/a/g, "b") → "b b b". Always use /g for replace-all operations.

How do I replace with a literal dollar sign?

Use $$ to insert a literal $. Since $ has special meaning in replacement strings ($1, $&, etc.), you need to escape it. Example: "price".replace(/price/, "$$100") → "$100". In the replacement string, $$ becomes a single $.

Related Tools

Explore other tools you might find useful:

Related Calculators