Regex Tester

Write a JavaScript regular expression and see every match highlighted live, with capture groups, named groups, and a replace preview. It runs on the browser's own RegExp engine, so what you see is what your code will do. 100% client-side, nothing leaves your browser.

2-Step Workflow Vanilla JS Developer Utility
🧪

Pattern & test string

/ / g
Presets:
🖍️

Highlighted matches

Type a pattern to see matches.
📋

Match details

No matches yet.

🔁

Replace preview

Enter a replacement string to preview the result.

How the Regex Tester works

A walkthrough of the two pieces that matter: a safe match loop that survives zero-length matches and bad patterns, and the highlighter that turns match offsets back into markup without breaking on HTML characters.

01

Build a safe match loop

Complete

Why learn this

A regex tester is only trustworthy if it uses the same engine your code will use. Reimplementing regex in a parser would drift from real behavior in subtle ways. The browser already ships a complete engine; the work is wrapping it so that invalid patterns, flag combinations, and empty matches never hang or crash the page.

What you built

A function that compiles the pattern with the selected flags, catches the SyntaxError a bad pattern throws, and collects every match with its index, captured groups, and named groups. It always runs a g-flagged copy of the regex so it can iterate with exec, and it only reports the first match when the user has the global flag off.

Key concepts

  • Compile once per keystroke. new RegExp(source, flags) throws on invalid input. Wrap it in try/catch and show the engine's own message — it is more accurate than anything you could write.
  • Zero-length matches loop forever. A pattern like a* matches the empty string, and exec does not move lastIndex forward. If m[0] === '', advance lastIndex by one manually.
  • Cap the results. Stop after 1,000 matches. A pattern like . on a large paste would otherwise produce a huge table and freeze the layout.
  • Sticky and global together. With y the engine only matches at lastIndex, so the loop ends at the first gap. That is the correct behavior, and the tester shows it rather than hiding it.
  • Named groups. m.groups is undefined when the pattern has no named groups, so guard before reading it.

Alternative approaches

String.prototype.matchAll returns an iterator and handles lastIndex for you, including empty matches, but it throws if the regex lacks the g flag and gives you less control over a hard result cap. A manual exec loop is a few more lines and makes the limit and sticky behavior explicit.

Browser compatibility

The g i m s u y flags and named groups are supported in current Chrome, Edge, Firefox, and Safari. The s (dotAll) flag and named groups need a reasonably recent browser; if the engine does not support them, the compile step throws and the error box says so.

Performance notes

The tester runs synchronously on the main thread, so a pattern with catastrophic backtracking — such as (a+)+$ against a long run of a followed by b — will freeze the tab. JavaScript cannot interrupt a running regex. For production code that accepts user-supplied patterns, run them in a Web Worker you can terminate.

Common pitfalls

  • Reusing a global regex. A g regex keeps lastIndex between test calls, so the same input alternates between true and false. Build a fresh regex or reset lastIndex to 0.
  • Escaping in strings. In a string literal you must write '\\d+'; in a regex literal you write /\d+/. The tester takes the raw pattern, so paste the regex-literal form.
  • Forgetting anchors. Without ^ and $, a validation pattern matches any substring. \d+ accepts abc123def.
  • Greedy quantifiers. <.+> swallows everything between the first < and the last >. Use <.+?> or <[^>]+>.
JS — Compile with error handling
function compile(source, flags) {
  try {
    return { re: new RegExp(source, flags) };
  } catch (e) {
    return { error: e.message };
  }
}
JS — Collect matches safely
const MAX = 1000;

function collect(re, text, isGlobal) {
  const out = [];
  re.lastIndex = 0;
  let m;
  while ((m = re.exec(text)) !== null) {
    out.push({
      text: m[0],
      index: m.index,
      groups: m.slice(1),
      named: m.groups || null
    });
    if (!isGlobal || out.length >= MAX) break;
    if (m[0] === '') re.lastIndex++;
  }
  return out;
}
💡 Tip

Always call exec on a regex that has g or y; without either, lastIndex is ignored and the loop returns the same first match forever. The tester adds g internally and only reports one match when the user's flag is off.

02

Highlight matches and preview replacements

Complete

Why learn this

Seeing the match in context is what makes a regex tester useful. The highlighter has to map match offsets back onto the original text and wrap them in markup, while treating the test string as untrusted text. A test string containing <script> must show up as literal characters, not execute.

What you built

A renderer that walks the match list in order, escapes the plain text between matches, wraps each match in a <mark> element (alternating two colors so adjacent matches stay distinguishable), and writes the result once. A second panel runs String.prototype.replace with the user's replacement string so $1, $&, and $<name> work exactly as they do in real code.

Key concepts

  • Escape everything. Every slice of the test string passes through an HTML escaper for &, <, and > before it is joined into markup. Never set innerHTML from raw input.
  • Slice by offsets. Keep a cursor. For each match, emit text.slice(cursor, m.index) as plain text, then the match as a mark, then move the cursor to m.index + m.text.length.
  • Skip empty matches when marking. A zero-length match has nothing to highlight, so it counts in the total but produces no mark.
  • Reuse the real replace. Calling text.replace(re, replacement) is the whole feature. The browser implements the substitution tokens, so there is nothing to get subtly wrong.
  • Escape the output, not just the input. The replace result is displayed through textContent, which needs no escaping and cannot inject markup.

Alternative approaches

A transparent textarea layered over a highlighted div gives live highlighting while you type inside the text area itself, but it needs scroll syncing and font-metric matching to stay aligned. A separate read-only highlight panel is simpler and never drifts. The tradeoff is that you edit in one place and read in another.

Browser compatibility

The renderer uses textContent, innerHTML, and String.prototype.replace, all available everywhere. Clipboard copy uses navigator.clipboard with a hidden-textarea fallback for older or non-secure contexts.

Performance notes

Rendering builds one string and assigns it once, so even 1,000 marks cost a single layout pass. The match table is also capped at the first 200 rows to keep the DOM small, while the summary still reports the true total.

Common pitfalls

  • Injecting unescaped text. Setting innerHTML from the test string is an XSS hole, even in a local tool, because users paste content from elsewhere.
  • Offsets after replacement. Match indices refer to the original string. Highlight the original, and show the replacement in its own panel.
  • Unicode length. Without the u flag, an emoji is two UTF-16 code units, and . matches only half of it. Turn on u when the text contains astral characters.
  • Overlapping highlights. Matches from one exec loop never overlap, so a simple cursor is enough. Do not try to merge ranges from several different patterns into the same pass.
JS — Escape and highlight
function esc(s) {
  return s.replace(/&/g, '&amp;')
          .replace(/</g, '&lt;')
          .replace(/>/g, '&gt;');
}

function highlight(text, matches) {
  let html = '', cursor = 0, alt = false;
  for (const m of matches) {
    if (m.text === '') continue;
    html += esc(text.slice(cursor, m.index));
    html += '<mark' + (alt ? ' class="alt"' : '') + '>' +
            esc(m.text) + '</mark>';
    cursor = m.index + m.text.length;
    alt = !alt;
  }
  return html + esc(text.slice(cursor));
}
JS — Replace preview
function previewReplace(re, text, repl) {
  re.lastIndex = 0;
  return text.replace(re, repl);
}

// 'ada@example.com'.replace(
//   /(\w+)@(\w+)\.com/, '$2: $1')
// => 'example: ada'
💡 Tip

Alternate two highlight colors. With a single color, two adjacent matches such as abab against /ab/g read as one long match, which hides exactly the thing you are testing.

Engine
Native RegExp
Flags
6
Match cap
1,000
Steps
2

Built with vanilla JS, no dependencies. Matching, highlighting, and replacement all run in the browser on the engine your own code will use, so nothing you type is sent anywhere.

Lessons Learned — Build Process

Notes from building the match loop and the highlighter.

♾️
Zero-length matches are the classic hang

The first draft froze the tab on a*. exec returns an empty match without advancing lastIndex, so the loop never ended. One line, bumping lastIndex after an empty match, fixed it.

🧱
Use the real engine, not a model of it

Delegating compile, match, and replace to RegExp means the tool cannot disagree with your code, and the error messages come for free. Every line of regex logic we did not write is a line that cannot be wrong.

🛡️
Escape before you mark

Highlighting needs innerHTML, which makes escaping mandatory. Escaping each slice separately, before wrapping matches in <mark>, keeps pasted markup inert.

⏱️
Backtracking cannot be interrupted

A synchronous regex cannot be cancelled from the same thread. The tester documents this limit rather than pretending a timeout exists. A Web Worker is the fix if you need one.