v136 · javascript

Find & Replace

A real find-and-replace editor powered by RegExp.escape(). Type any literal string in the Find box — dots, dollars, asterisks, parens — and it's treated as a literal, not a regex metasymbol. Toggle Regex mode to disable escaping and allow full regex syntax. The "bad" column shows what a naive new RegExp(input) does with the same text.

Feature detection: checking…
Find & Replace enter a search term above
Type a search term to see matches
new RegExp(input) — metasymbols break it
waiting for input…
RegExp.escape() — safe literal matching
waiting for input…

Word boundaries are useful when the literal begins and ends with word characters. When the literal starts with a symbol, such as $price, \b can miss the exact token; a word-character lookaround is the safer pattern.

Naive whole word

0 matches

Escaped literal with lookaround

0 matches
function buildPattern(input, opts) {
  const escaped = opts.regex
    ? input               // user wants real regex
    : RegExp.escape(input); // literal match — safe from user input

  const flags = 'g' + (opts.case ? 'i' : '');
  const source = opts.word
    ? `\\b${escaped}\\b`  // whole-word boundary
    : escaped;

  return new RegExp(source, flags);
}

// Find all
const pattern = buildPattern(findInput.value, { case, word, regex });
const matches = [...document.body.textContent.matchAll(pattern)];

// Replace all
const result = original.replaceAll(pattern, replaceWith);

see also