Skip to content
Text 7 min read

Find & Replace with Regex: Power Text Editing Techniques

Master find and replace with regular expressions: capture groups, backreferences in replacements, multiline matching, and practical patterns for bulk text transformations.

ToolsVito Team

Basic Find and Replace

// JavaScript — String.replace with regex
"Hello World".replace(/World/, "Universe");
// "Hello Universe"

// Global flag — replace all occurrences
"aaa".replace(/a/g, "b");
// "bbb"

// Case-insensitive
"Hello HELLO".replace(/hello/gi, "Hi");
// "Hi Hi"

Capture Groups in Replacements

Capture groups ((...)) let you reuse matched text in the replacement string:

// Swap first and last name
"Doe, John".replace(/(w+), (w+)/, "$2 $1");
// "John Doe"
// $1 = "Doe", $2 = "John"

// Wrap words in <strong> tags
"hello world".replace(/(w+)/g, "<strong>$1</strong>");
// "<strong>hello</strong> <strong>world</strong>"

// Add quotes around values
"color: red".replace(/: (w+)/, ': "$1"');
// 'color: "red"'

Named Capture Groups

// Named groups: (?<name>...)
// Replacement: $<name>
"2024-01-15".replace(/(?<year>d{4})-(?<month>d{2})-(?<day>d{2})/, "$<day>/$<month>/$<year>");
// "15/01/2024"

Replacement Function

Pass a function instead of a string for dynamic replacements:

// Convert hex colors to uppercase
"color: #ff4d8b".replace(/#([0-9a-f]+)/gi, (match, hex) => "#" + hex.toUpperCase());
// "color: #FF4D8B"

// Replace with calculated values
"price: $100".replace(/$(d+)/, (match, amount) => `$${parseInt(amount) * 1.1}`);
// "price: $110"

// Replace all numbers with their doubles
"1 plus 2 equals 3".replace(/d+/g, n => String(parseInt(n) * 2));
// "2 plus 4 equals 6"

Multiline Mode

const text = `line one
line two
line three`;

// Without multiline flag: ^ and $ match start/end of entire string
text.replace(/^line/g, "row");  // only replaces "line" at start of string

// With multiline flag: ^ and $ match each line boundary
text.replace(/^line/gm, "row");
// "row one\nrow two\nrow three"

Practical Bulk Transformation Examples

// Convert CSS custom properties to Tailwind-style comments
"--color-primary: #0a0a0a".replace(/--([w-]+)/, "/* $1 */");

// Convert snake_case to camelCase
"user_first_name".replace(/_(w)/g, (_, char) => char.toUpperCase());
// "userFirstName"

// Wrap all URLs in anchor tags
text.replace(/(https?://[^s<]+)/g, '<a href="$1">$1</a>');

// Remove all HTML comments
html.replace(/<!--[sS]*?-->/g, "");

// Convert markdown bold to HTML
"**text**".replace(/**([^*]+)**/g, "<strong>$1</strong>");

Bulk Find & Replace Instantly

Use ToolsVito's Find & Replace tool to apply regex replacements to any text in your browser — with live preview and multiline support.

Try it now — free, runs in your browser

Find & Replace

Bulk text replace, with regex