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.
Pattern & test string
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.
Build a safe match loop
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 intry/catchand 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, andexecdoes not movelastIndexforward. Ifm[0] === '', advancelastIndexby 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
ythe engine only matches atlastIndex, 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.groupsisundefinedwhen 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
gregex keepslastIndexbetweentestcalls, so the same input alternates between true and false. Build a fresh regex or resetlastIndexto 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+acceptsabc123def. - Greedy quantifiers.
<.+>swallows everything between the first<and the last>. Use<.+?>or<[^>]+>.
function compile(source, flags) {
try {
return { re: new RegExp(source, flags) };
} catch (e) {
return { error: e.message };
}
} 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;
} 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.
Highlight matches and preview replacements
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 setinnerHTMLfrom 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 tom.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
innerHTMLfrom 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
uflag, an emoji is two UTF-16 code units, and.matches only half of it. Turn onuwhen the text contains astral characters. - Overlapping highlights. Matches from one
execloop never overlap, so a simple cursor is enough. Do not try to merge ranges from several different patterns into the same pass.
function esc(s) {
return s.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
}
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));
} function previewReplace(re, text, repl) {
re.lastIndex = 0;
return text.replace(re, repl);
}
// 'ada@example.com'.replace(
// /(\w+)@(\w+)\.com/, '$2: $1')
// => 'example: ada' 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.
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.
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.
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.
Highlighting needs innerHTML, which makes escaping mandatory. Escaping each slice separately, before wrapping matches in <mark>, keeps pasted markup inert.
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.