Skip to content

general guide

JavaScript Regex Explained: Flags, Groups, Lookarounds and the Backtracking Trap

A regular expression is a small program that searches for a shape in text, and most regex frustration comes from assuming it behaves like the one in another language. JavaScript's engine has its own rules: a dot stops at four different line-break characters, an empty character class is legal and matches nothing, alternation takes the first branch that works rather than the longest, and adding the u flag can turn a pattern that ran for years into a syntax error. Then there is the failure mode that is not about correctness at all — a pattern that is right but takes exponential time on input that almost matches. This guide covers the semantics with the actual measured results, and the backtracking trap with timings you can reproduce.

Updated December 2, 2026 · 16 questions answered

Key takeaways

  • The tester uses your browser's own RegExp object, so a pattern that works there works in your JavaScript on the same engine. It is not a separate dialect.
  • Six flags are offered: g, i, m, s, u and y. Without g you get only the first match, and a replacement changes only the first occurrence.
  • A dot excludes four characters, not one: line feed, carriage return, U+2028 and U+2029. The s flag lifts that restriction; the class [^] achieves the same without a flag.
  • Alternation is ordered, not longest-match. The pattern ab|abc against the text abc returns ab, because the first branch already succeeded.
  • JavaScript character classes are not POSIX ones. An empty class [] is valid and never matches; [^] matches any character including a line break.
  • Nested quantifiers over overlapping alternatives can make matching exponential. Measured: a 24-character near-miss took 145ms where the rewritten pattern handled 100,000 characters instantly.

The Engine Is Your Browser's Own, and That Is the Whole Point

The regex tester compiles your pattern with new RegExp(pattern, flags) and runs it against the subject using the browser's native engine. There is no reimplementation, no transpilation to another dialect and no server round trip. That matters more than it sounds: a regex is only useful if it behaves the same way in the place you will actually run it, and a tester built on a different engine can agree with you right up to the moment it does not.

The corollary is that results are engine-specific in the honest sense. Chrome, Edge and Node share V8; Firefox uses SpiderMonkey; Safari uses JavaScriptCore. All three implement ECMAScript regex, so the core semantics agree, but they differ at the edges — lookbehind arrived in Safari only in 16.4, and performance characteristics differ substantially even when the match result is identical. If your pattern will run in Node, testing in Chrome is testing the same engine.

Everything stays on your device, which is the reason to prefer a local tester for the text people actually paste into one: log lines carrying tokens, customer records, a configuration dump, an email archive. You can confirm it yourself by opening the Network panel before typing — there is no request to observe.

The tool also explains the pattern token by token, naming each escape, quantifier, group and lookaround in plain language. That is deliberately surface-level: it tells you what the syntax asks for, not what you meant. For an unfamiliar pattern inherited from someone else's code, reading the explanation next to the highlighted matches is usually faster than reasoning through the shorthand, and it is how you catch a construct you did not know was there.

Two limits are worth knowing before you trust a result. Matches are capped at 1,000 with a visible truncation flag, so a pattern that hits the cap is reporting a sample rather than a total. And a pattern that is syntactically invalid produces the engine's own SyntaxError message rather than a guess — an unclosed [ is reported as such, which is the correct answer and not a failure of the tool.

Six Flags, and What Each One Actually Changes

g — global. Without it, matching stops after the first hit and a replacement changes only the first occurrence. Measured: the digits in a1b2c3 give one match without g and three with it; replacing a digit with X gives aXb2 without g and aXbX with it. This is the single most common reason a replacement "only worked once". The tester defaults to g and i together, which is a sensible starting point for searching text.

i — ignore case. ABC does not match /abc/ but does match /abc/i. What i does *not* do by default is full Unicode case folding. Measured: the Kelvin sign at U+212A does not match /k/i, but does match /k/iu. Adding u enables simple folding, where one code point maps to one other code point. It still does not enable full folding, where one character maps to several: neither /straße/iu against STRASSE nor /STRASSE/iu against straße matches. If you need that equivalence, normalise the strings before comparing rather than expecting a flag to do it.

m — multiline. Changes what ^ and $ mean: with m they match at every line boundary, without it only at the start and end of the whole subject. Measured: /^b/ finds nothing in a two-line string where b starts the second line, and /^b/m finds it. There is a related asymmetry people expect from Perl and do not get here — without m, $ does not match just before a trailing newline. a followed by a newline does not match /a$/, but does match /a$/m.

s — dotAll. A dot normally excludes four characters: line feed, carriage return, U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR. All four were verified to block a match. With s, the dot matches any character including a line break. The flag-free equivalent is the negated empty class [^], which matches everything — a genuinely useful idiom when you cannot add a flag, and one that only makes sense once you know JavaScript's class rules below.

u — Unicode. Treats the pattern and subject as code points rather than UTF-16 code units, so an emoji is one character instead of two. Measured: a single emoji gives one match with /./gu and two with /./g. It also enables \p{...} property escapes and stricter parsing — and that strictness is a trap. Without u, \q is an identity escape meaning a literal q. With u, it is a SyntaxError: Invalid escape. Adding u to a working pattern can therefore break it.

y — sticky. Matches only at exactly lastIndex, with no searching forward. Measured: with lastIndex at 1, /a/y fails against ab because position 1 holds b, but succeeds against ba. The global flag from the same position skips ahead and finds the a at index 2 in bba. Sticky is for tokenisers that must consume input consecutively; global is for finding things anywhere.

Two flags exist in the engine but are not offered here, and it is worth being explicit about that rather than implying full coverage. d adds an indices property giving the start and end of the whole match and of every capture group — verified working in V8. v is the upgraded Unicode mode with set intersection and subtraction inside classes, so [[a]&&[a]] and nested [[a]] become meaningful. Both are real; neither is exposed by this tester's flag row.

Groups: Numbered, Named, Non-Capturing, and Back-References

Parentheses do two jobs at once: they group for quantifiers and alternation, and they capture. Numbering is by the order of the opening parenthesis, left to right, starting at 1. Measured against 2026-12-02, the pattern (\d{4})-(\d{2})-(\d{2}) captures 2026, 12 and 02 in groups 1, 2 and 3. Group 0 is always the whole match.

Named groups use (?<name>...) and are readable in the result's groups object. They also have a back-reference form, \k<name>, which matches the same text the group captured earlier — verified with (?<w>\w+) \k<w> matching hi hi but not hi there. Names are not a substitute for numbers: a named group still occupies a numbered slot, so inserting one shifts every later number.

Non-capturing groups (?:...) group without taking a slot. Measured: (?:a)(b) against ab captures only b. Use them whenever you need parentheses for structure — applying a quantifier to several characters, or scoping an alternation — but do not want the text back. They keep group numbers stable, which matters the moment a pattern is used in a replacement string.

A back-reference to a group that did not participate matches the empty string, not a failure. Measured: (a)?b\1 matches plain b, because the optional group never captured and \1 therefore asks for nothing. This is standard ECMAScript behaviour and differs from some other engines, where an unmatched back-reference fails the match. It is a subtle source of patterns that accept more than you intended.

In a replacement string, $1 through $99 insert numbered groups and $<name> inserts a named one. Measured: rewriting 2026-12-02 with $3/$2/$1 gives 02/12/2026, and the named-group equivalent $<d>/$<m>/$<y> gives the same. Four special forms are easy to forget: $& is the whole match, ` $ ` is everything before it, $' is everything after it, and $$ is a literal dollar sign. Verified: replacing b in abc with <$|$'> ` produces a<a|c>c. That last one is why a replacement containing a currency amount needs $$`.

Greedy, Lazy, and Why Alternation Takes the First Branch

A quantifier is greedy by default: *, +, ? and {n,m} take as much as they can while still allowing the rest of the pattern to match. Appending ? makes it lazy, taking as little as possible. The classic demonstration is markup: against <b>x</b>, the greedy <.*> returns one match spanning the whole string, while the lazy <.*?> returns two, <b> and </b>. Neither is wrong; they answer different questions.

The important nuance is that lazy does not mean "shortest possible overall". It means "shortest at this position, then try to finish the pattern". The engine still scans left to right and still backtracks when the remainder fails. A lazy quantifier can therefore still be slow, and it can still produce a longer match than you expect if the rest of the pattern forces it to expand.

{n,m} has three forms worth distinguishing: {3} exactly three, {3,} three or more, {3,5} between three and five. A brace that does not form a valid quantifier is treated as literal text — measured, a{b matches the four characters a{b rather than raising an error. That leniency is convenient and occasionally surprising.

Alternation is ordered, not longest-match. This is the rule that most often contradicts intuition carried over from other tools. Measured: /ab|abc/ against abc returns ab, because the first branch succeeded and the engine does not go back to look for a longer one. If you want the longest, put the longer alternative first: abc|ab. The same applies inside groups, and it is why a pattern that "works on the test string" fails on a slightly different one.

Anchors and boundaries are zero-width: they assert a position without consuming a character. ^ and $ assert the start and end (of the subject, or of each line with m), and \b asserts a transition between a word character and a non-word character. Measured: \bcat\b against cat scatter cat returns two matches, correctly ignoring the cat inside scatter. Because they consume nothing, /^/gm against a two-line string returns two empty matches — which is exactly the zero-length case the next section deals with.

Lookarounds: Asserting a Position Without Consuming It

A lookaround checks what is next to the current position without including it in the match. There are four, and the tester's explainer names all of them: (?=...) positive lookahead, (?!...) negative lookahead, (?<=...) positive lookbehind, (?<!...) negative lookbehind.

Measured: foo(?=bar) against foobar returns foo — the bar was required but not consumed. foo(?!bar) against foobaz also returns foo, because what follows is not bar. (?<=USD)\d+ against USD100 returns 100, with the currency prefix asserted but excluded. That last one is the reason lookbehind exists: without it you would capture USD100 and then strip the prefix in code.

The practical payoff is that lookarounds let you match a thing by its context rather than matching the context and discarding it. Password rules are the canonical example: several negative lookaheads at the start assert the absence of a run of digits or a repeated character, while the consuming part of the pattern matches the whole string. Splitting a camel-case identifier, inserting a separator before a capital that follows a lowercase, or finding a number that is not part of a longer token are all lookaround jobs.

Two cautions. Lookbehind must be fixed-length in JavaScript — (?<=a+) is a syntax error, unlike in .NET where variable-length lookbehind is allowed. And lookbehind is the newest of the four: it is absent in Safari before 16.4 and in older Node releases, so a pattern using it is not portable to every runtime that otherwise supports modern regex. If you need to support those, restructure with a capture group and post-processing.

Lookarounds are also zero-width, which means they can succeed at a position where nothing is consumed. Combined with a global flag that is the setup for the zero-length-match behaviour below, and it is worth remembering that a pattern made entirely of assertions can match at every position in the subject.

Character Classes: JavaScript Is Not POSIX, and [] Is Legal

A class [...] matches one character from a set. [^...] negates it. Ranges use a hyphen, and a hyphen at the start or end is a literal. Escapes work inside classes, so [\d\s] is digits or whitespace. All of that is uncontroversial. The part that differs from other regex dialects is what happens when the first character after the opening bracket is a closing bracket.

In POSIX and PCRE, a ] immediately after [ or [^ is a literal member of the set, so []a] means "the set containing ] and a". In JavaScript it is not: the ] closes the class, leaving an empty set. Measured against the subject ]a-abc, []a] returns no match at all. What the engine actually sees is an empty class followed by the two literal characters a and ] — a pattern that can never match anything, because its first element is unsatisfiable.

Two consequences are worth memorising. [] is a valid empty class that never matches. It is not a syntax error. [^] is a negated empty class, so it matches every character including a line break — verified against a string containing a newline. That makes [^] the flag-free way to write "any character at all", equivalent to a dot with the s flag, and it is a common idiom in minified code precisely because it is shorter than (.|\n).

If you want a literal closing bracket inside a set, escape it: [\]a] is the portable form and correctly matches ] or a. Measured, it returns three hits against ]a-abc where the unescaped version returned none. Outside a class a ] needs no escape at all and is simply a literal character.

The v flag changes the internals but not these two cases. Verified under v: [] still never matches and [^] still matches everything, while nested classes [[a]] and set intersection [[a]&&[a]] become meaningful. Without v, /[[a]]/ is a class containing [ and a followed by a literal ], which is why it matches a] inside the string [a]. Same characters, two different parses, decided entirely by a flag.

This distinction is not academic for a tester that explains patterns. An explainer using POSIX rules would confidently describe []a] as "any character from the set ]a" while the engine matches nothing — a plausible sentence that is simply false. The explainer here follows JavaScript's rules and states the empty and negated-empty cases explicitly, so the description and the highlighted matches cannot disagree.

Zero-Length Matches, and the Loop That Would Never End

A pattern can match the empty string: a*, ^, \b, (?=x) and any optional-only construct all do. That is legal and often useful, but it breaks the naive way of walking a global regex, because the engine's cursor does not advance past a match that consumed nothing.

Measured with /a*/g against bab: the matches are an empty string at index 0, a at index 1, an empty string at index 2 and an empty string at index 3 — four results, three of them empty. After the empty match at index 0, lastIndex is still 0. Call exec again without adjusting it and you get the identical empty match forever.

The tester handles this the way every correct implementation does: after a zero-length match it advances lastIndex by one before continuing. That is why the walk terminates and why you see the empty matches at all. The display marks them with a ␀ symbol so an invisible result is still visible in the list, rather than appearing as a blank row you might mistake for a rendering bug.

Two related cursor behaviours are worth knowing when you reuse a regex object. After a global exec fails, lastIndex resets to 0 — verified going from 1 back to 0 — so a regex that found nothing is ready to search again from the start. And a regex literal is not cached: evaluating /a/g twice produces two distinct objects, each with its own lastIndex. Building the regex inside a loop is therefore safe but wasteful; building it once outside and reusing it is faster, provided you remember the cursor is shared.

The practical rule for your own code: never write while ((m = re.exec(s)) !== null) without handling the zero-length case. Either advance lastIndex manually as the tester does, or use s.matchAll(re), which handles it for you and requires the global flag. The infinite loop is not a hypothetical — it is the default outcome of the obvious implementation.

Catastrophic Backtracking: Measured, and How to Rewrite It

A backtracking engine tries a path, and when the rest of the pattern fails it returns to the last decision point and tries another. With nested quantifiers over overlapping alternatives, the number of paths grows exponentially with input length. The pattern still gives the right answer — it just takes longer than the heat death of the universe to get there on a near-miss.

The canonical example is ^(a+)+$ against a run of a characters followed by something that cannot match. Measured in V8, with the regex compiled first so compilation is not counted: 16 characters took under a millisecond, 18 took 3ms, 20 took 9ms, 22 took 38ms and 24 took 145ms. Each extra two characters roughly quadruples the time, which is the signature of 2^n growth. At 40 characters the same pattern would run for hours; at 60, for years.

The fix is to remove the ambiguity. ^a+$ expresses exactly the same language — one or more a characters and nothing else — and measured against 100,000 characters it completed in under a millisecond. The outer group added no expressive power, only exponentially many ways to partition the same run. That is the general shape of the remedy: if two nested quantifiers can both claim the same characters, collapse them.

Not every nested quantifier is catastrophic, and it is worth being precise rather than fearful. ^(a|aa)+$ also has overlapping alternatives, but measured at 22 characters it completed in under a millisecond, because the number of partitions grows like the Fibonacci sequence rather than 2^n. The danger is specifically an inner quantifier that can match a variable number of the same characters, wrapped in an outer quantifier, followed by something that can fail. Ambiguity plus a late failure is the combination.

The standard PCRE remedies are not available here, which is the part most advice gets wrong for JavaScript. Atomic groups (?>a+) and possessive quantifiers a++ both raise SyntaxError in V8 — verified. You cannot tell the engine to stop backtracking; you have to rewrite the pattern so there is nothing to backtrack over. Restructuring with a lookahead, anchoring earlier, or replacing the nested quantifier with a single one are the available tools.

Two defences matter as much as the rewrite. Bound the input length before matching untrusted text, since exponential cost is a denial-of-service vector when the pattern comes from a user. And prefer a linear-time engine for untrusted patterns — RE2, used by Go and by some database engines, guarantees no catastrophic backtracking by refusing constructs that need it. The trade is that RE2 has no lookaround and no back-references, so it is a different tool for a different threat model, not a drop-in replacement.

A Routine for Any Unfamiliar Pattern

Most regex debugging is the same five questions in the same order, and having them memorised turns a fiddly job into a reflex. One: is g set? If you expected every occurrence and got one, that is the answer, and it also explains a replacement that only changed the first hit. Two: does the pattern span lines? If so, a dot will not cross a newline without s or [^], and ^ and $ will not mean line boundaries without m.

Three: are the groups numbered the way the replacement assumes? Inserting a capturing group shifts every later number, which is why (?:...) exists. Four: is alternation ordered longest-first? /ab|abc/ will never return abc. Five: does the pattern contain a nested quantifier over overlapping alternatives? If it does and the input is untrusted, rewrite it before deploying it.

Then test the near-miss, not just the happy path. A pattern that matches correctly on valid input can still hang on input that is one character away from valid, and that is exactly the case an attacker or a malformed log line will supply. The backtracking timings above came from a string of a characters with a single b appended — the match fails, and the failure is what costs the time.

For text work that is mechanical rather than pattern-shaped, a dedicated tool is usually clearer and safer than a hand-written expression. Case conversion, whitespace cleanup, duplicate-line removal, slug generation and tag stripping all have fixed contracts, and the online text tools guide covers which job belongs to which tool. Reach for a regex when the shape is genuinely variable; reach for a purpose-built tool when it is not. And when a pattern is extracting structure out of JSON or a token, decode first and match second — the JSON formatter guide explains why matching against an encoded string is the harder version of the same job.

Frequently asked questions

The questions people ask most about regex guide: flags, groups and backtracking, answered directly.

Why does my regex only replace the first occurrence?

Because the global flag is not set. Without g, both matching and replacement stop after the first hit. Measured: replacing a digit with X in a1b2 gives aXb2 without g and aXbX with it. Add g to the flags, or use replaceAll, which requires g and throws without it.

What is the difference between the s flag and the m flag?

They change different things. s makes the dot match line breaks as well, so a.b can span two lines. m makes the anchors ^ and $ match at every line boundary instead of only at the start and end of the whole subject. You often want both together when processing multi-line text.

Does a dot match a newline in JavaScript?

No. A dot excludes four characters: line feed, carriage return, U+2028 and U+2029. All four were verified to block a match. Use the s flag to include them, or the negated empty class [^], which matches any character including a line break without needing a flag.

What does the u flag actually change?

It treats the pattern and subject as Unicode code points rather than UTF-16 code units, so an emoji counts as one character instead of two. It enables property escapes like \p{L}, enables simple Unicode case folding, and makes invalid escapes such as \q a syntax error instead of a literal q. It does not make \w match accented letters.

Does the u flag make \w match accented characters?

No, and this is a common misconception. Measured on a word ending in an accented e, \w+ stops before the accent both with and without u. To match letters across scripts use \p{L} with the u flag. Without u, \p{L} is not an error but silently means a literal p followed by {L}, which is worse than failing.

Why does alternation return the shorter match?

Because JavaScript alternation is ordered, not longest-match. The engine tries branches left to right and accepts the first that lets the overall pattern succeed. Measured: ab|abc against abc returns ab. Put the longer alternative first, abc|ab, when you want the longest.

What is the difference between greedy and lazy quantifiers?

A greedy quantifier takes as much as it can while still allowing the rest of the pattern to match; a lazy one, written with a trailing question mark, takes as little as possible. Against <b>x</b>, the greedy <.*> returns the whole string as one match while the lazy <.*?> returns the two tags separately. Lazy does not guarantee the shortest overall result.

Is [] a valid regular expression in JavaScript?

Yes. It is an empty character class, and it never matches anything. JavaScript does not follow the POSIX rule where a closing bracket immediately after the opening one is a literal member. So []a] is an empty class followed by the literal characters a and ], which can never match. Use [\]a] to include a literal bracket.

What does [^] match?

Every character, including a line break. It is a negated empty class, so nothing is excluded. This is a standard JavaScript idiom for any character at all, equivalent to a dot with the s flag, and it is why you see it in minified code. It was verified against a string containing a newline.

What is catastrophic backtracking?

Exponential matching time caused by nested quantifiers over overlapping alternatives, triggered by input that almost matches. Measured on ^(a+)+$ against a run of a characters plus one b: 16 characters took under a millisecond, 20 took 9ms, 22 took 38ms and 24 took 145ms, roughly quadrupling every two characters. The answer is still correct; it just arrives too late to be useful.

How do I fix a regex that backtracks catastrophically?

Remove the ambiguity. Rewriting ^(a+)+$ as ^a+$ expresses the same language and handled 100,000 characters in under a millisecond. Also bound the input length for untrusted text. Note that atomic groups (?>...) and possessive quantifiers a++ are syntax errors in JavaScript, so the usual PCRE remedies are unavailable and a rewrite is required.

Does JavaScript support lookbehind?

Yes, both positive (?<=...) and negative (?<!...), and it must be fixed-length: (?<=a+) is a syntax error. Support arrived in Safari 16.4; older Safari and older Node releases lack it, so a lookbehind pattern is not portable to every runtime that otherwise supports modern regex. Measured: (?<=USD)\d+ against USD100 returns 100.

What is a non-capturing group and when should I use one?

(?:...) groups characters for a quantifier or alternation without assigning a capture number. Measured: (?:a)(b) against ab captures only b. Use it whenever you need structure but not the text back, because it keeps group numbers stable, which matters as soon as the pattern is used in a replacement string.

What do $&, $$ and $1 mean in a replacement string?

$1 through $99 insert numbered capture groups and $<name> inserts a named one. $& inserts the whole match, $` inserts everything before the match, $' inserts everything after it, and $$ inserts a literal dollar sign. Measured: replacing b in abc with <$`|$'> produces a<a|c>c.

Why does my global regex loop forever on some patterns?

Because a zero-length match does not advance lastIndex, so the next exec returns the identical empty match. Patterns like a*, ^ or a lookahead can match empty. After a zero-length result you must increment lastIndex yourself, or use matchAll, which handles it. The tester advances by one and marks empty matches with a symbol so they are visible.

What does the y (sticky) flag do?

It matches only at exactly lastIndex, with no searching forward. Measured with lastIndex at 1: /a/y fails against ab because position 1 holds b, but succeeds against ba. The global flag from the same position would skip ahead and find a later a. Sticky is for tokenisers that must consume input consecutively.