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
| Syntax | Meaning | Example |
$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
| Task | Pattern | Replacement |
Trim whitespace^\s+\\s+$''
Collapse spaces\s+' '
Remove HTML tags<[^>]+>''
Escape HTML[&<>"']Function
Normalize newlines\r\n?\\n'\n'`