JavaScript Regex Explained: Patterns, Flags, Groups and Pitfalls
JavaScript regex lets you search, extract, validate and replace text with compact patterns. Learn test, match, matchAll and replace, every flag including u, v and d, capture and named groups, lookarounds, greedy versus lazy matching, escaping user input, and the backtracking trap that froze our test for three seconds.
- JavaScript regex literals look like
/pattern/flags; usenew RegExp()when the pattern is built at runtime. - Without the
gflag,replacechanges only the first match andmatchreturns capture groups instead of all matches. - A global regex used with
test()rememberslastIndex: the same call returned true, true, then false in our test. - A nested quantifier like
/^(a+)+$/took 2,958 ms on a 27-character string; the fixed pattern took 0.04 ms.
Pulling order numbers from emails, validating form input, reformatting dates, splitting messy CSV-like text: regular expressions do all of these in one line. They also have a reputation for being write-only and dangerous. Most of that comes from a few behaviours that surprise people, so this guide covers the everyday API and those surprises with code we actually ran.
All examples ran in Node.js v24.22.1 and the output is shown as printed. Browsers use the same regex engine semantics. The concepts transfer to other languages; compare with our Python regex guide.
Creating a regular expression
const literal = /#\d+/g; // fixed pattern
const dynamic = new RegExp("#" + "\\d+", "g"); // built from strings
Prefer literals for fixed patterns: they are checked when the script loads and need no extra escaping. Use the constructor when the pattern comes from variables, but remember that backslashes in a string must be doubled. Our sample text for the rest of the article:
const text = "Order #1042 shipped 2026-11-23. Order #1043 pending. Contact help@shop.example or sales@shop.example.";
test, match and matchAll
/#\d+/.test(text) // true
text.match(/#(\d+)/) // [ '#1042', '1042', index: 6, ... ]
text.match(/#\d+/g) // [ '#1042', '#1043' ]
for (const m of text.matchAll(/Order #(?<id>\d+) (?<status>\w+)/g))
console.log(m.groups.id, m.groups.status, "at", m.index);
// 1042 shipped at 0
// 1043 pending at 32
testreturns a boolean: the right tool for validation.matchwithoutgreturns the first match with its capture groups and position; withgit returns all full matches but loses the groups.matchAll(requiresg) gives every match with groups and index, usually what you actually want when extracting data.
Replacing text
"a-b-c".replace("-", "+") // 'a+b-c' (first only)
"a-b-c".replace(/-/g, "+") // 'a+b+c'
"a-b-c".replaceAll("-", "+") // 'a+b+c'
"2026-11-23".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1") // '23/11/2026'
"2026-11-23".replace(/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/, "$<d>.$<m>.$<y>") // '23.11.2026'
"price 10 and 25".replace(/\d+/g, n => n * 2) // 'price 20 and 50'
The most common regex bug is forgetting g and replacing only the first occurrence. In the replacement string, $1 refers to the first group, $<name> to a named group, and $& to the whole match. Passing a function instead of a string lets you compute each replacement, here doubling every number.
Capture groups and named groups
Parentheses capture what they match. Named groups, (?<name>...), make code readable: m.groups.id beats m[1], and adding a group later does not shift every index. Use (?:...) for grouping without capturing, for example /(?:Mr|Ms)\.? (\w+)/ when you need alternation but not the title.
Regex syntax cheat sheet
| Pattern | Matches |
|---|---|
\d, \w, \s |
Digit, word character, whitespace |
\D, \W, \S |
The opposites |
. |
Any character except line breaks (unless s flag) |
[abc], [^abc], [a-z] |
One of, none of, a range |
*, +, ?, {2,4} |
0+, 1+, 0 or 1, between 2 and 4 |
^, $, \b |
Start, end, word boundary |
a|b |
Either a or b |
(...), (?:...), (?<n>...) |
Capture, non-capturing, named group |
All the regex flags
/order/i.test(text) // true (i: ignore case)
"a\nb".match(/^b/m)?.[0] // 'b' (m: ^ and $ match at each line)
"a\nb".match(/^b/) // null
/a.b/.test("a\nb") // false
/a.b/s.test("a\nb") // true (s: dot matches newlines)
/(?<id>\d+)/d.exec("ab123").indices.groups.id // [ 2, 5 ] (d: match positions)
| Flag | Effect |
|---|---|
g |
Global: all matches; enables matchAll |
i |
Case-insensitive |
m |
Multiline anchors |
s |
. also matches line breaks |
u |
Unicode mode: code points, \p{...} classes |
v |
Unicode sets: set operations in classes (newer engines) |
y |
Sticky: match only at lastIndex |
d |
Indices: start and end positions of groups |
The lastIndex trap with g and test
const g = /o/g;
g.test("foo"), g.test("foo"), g.test("foo") // true, true, false
g.lastIndex // 0
A regex with g or y is stateful: after each successful test or exec, it stores where it stopped in lastIndex and starts there next time. Reusing one global regex to validate many inputs therefore gives alternating, seemingly random results. Do not use the g flag for validation, or create the regex inside the function.
Tip: validation patterns should be anchored (^...$) and have no g flag. Extraction patterns use g with matchAll.
Greedy vs lazy quantifiers
"<b>x</b><b>y</b>".match(/<b>.*<\/b>/)[0] // '<b>x</b><b>y</b>' (greedy)
"<b>x</b><b>y</b>".match(/<b>.*?<\/b>/)[0] // '<b>x</b>' (lazy)
* and + grab as much as possible, then back off. Adding ? makes them lazy, taking as little as possible. Lazy quantifiers fix many “matched too much” bugs, though for real HTML a parser is the right tool, not a regex.
Lookahead and lookbehind
/^(?=.*\d)(?=.*[A-Z]).{8,}$/.test("Secret123") // true
/^(?=.*\d)(?=.*[A-Z]).{8,}$/.test("secret123") // false (no capital)
"cost ₹250 and $40".match(/(?<=₹)\d+/)[0] // '250'
Lookarounds check context without consuming it. Each (?=...) at the start asserts that a condition holds somewhere ahead, which is how one pattern enforces several password rules. Lookbehind (?<=₹) matched the amount after a rupee sign without including the sign. Lookbehind is supported in all current browsers and Node.js.
Unicode, emoji and the u and v flags
"😀".length // 2
/^.$/.test("😀") // false (two UTF-16 units)
/^.$/u.test("😀") // true
/[\p{L}--[a-z]]/v.test("A") // true (letters except a-z)
/[\p{L}--[a-z]]/v.test("a") // false
JavaScript strings are UTF-16, so emoji and many symbols take two code units. Without u, a dot matches half an emoji. Always use u (or the newer v) when text may contain non-ASCII characters; it also enables \p{L} for “any letter in any language”. The v flag adds set subtraction and intersection inside classes. Background on encodings is in our UTF-8 guide.
Escaping user input
const esc = s => s.replace(/[.*+?^${}()|[\]]/g, m => String.fromCharCode(92) + m);
esc("1+1=2?") // '1\+1=2\?'
new RegExp(esc("1+1")).test("x1+1y") // true
Building a regex from user input without escaping is a bug and can be a security issue: a search for 1+1 would otherwise mean “one or more 1s followed by 1”. Escape special characters first, as above; the full set also includes the backslash itself, which we left out of this short version. A built-in RegExp.escape() was added to the language recently and already exists in Node.js 24, as our check confirmed; check support in your target browsers before relying on it. The tighter email ending suggested below also passed our test, returning both addresses without the trailing full stop.
Catastrophic backtracking
const evil = /^(a+)+$/;
evil.test("a".repeat(26) + "b"); // 2958 ms
/^a+$/.test("a".repeat(26) + "b"); // 0.039 ms
Nested quantifiers like (a+)+ give the engine an exponential number of ways to split the input. When the match finally fails at the b, it tries them all: 27 characters took almost three seconds, and each extra character roughly doubles the time. This is the basis of ReDoS (regular expression denial of service) attacks, where a crafted input freezes a server. Avoid nested quantifiers over the same characters, prefer specific classes over .*, limit input length before matching, and test patterns against long non-matching strings.
A real bug we hit: the email pattern
text.match(/[\w.+-]+@[\w-]+\.[\w.]+/g)
// [ 'help@shop.example', 'sales@shop.example.' ]
The second email captured the sentence’s final full stop, because [\w.]+ happily includes dots. Our test caught it; a production system would have tried to email an invalid address. A tighter ending such as \.[a-z]{2,}\b fixes this case. Email addresses are notoriously hard to validate fully by regex: check basic shape, then confirm by sending a message. For splitting tokens, a simple pattern often suffices:
"a, b;c d".split(/[,;\s]+/) // [ 'a', 'b', 'c', 'd' ]
Regexes pair well with template literals when building output and with array methods when processing the matches.
Final thoughts
JavaScript regex is powerful once you know its rules: use g to replace or extract everything, matchAll to keep groups, named groups for readability, u for real-world text, and no g on validation patterns. Escape user input, avoid nested quantifiers, and always test patterns against tricky inputs, including the full stop at the end of a sentence. For URLs specifically, prefer the built-in URL parser covered in our URL encoding guide.
Frequently asked questions
How do I replace all matches in JavaScript?
Add the g flag to the regular expression, for example replace with a pattern ending in slash g, or use replaceAll with a plain string. Without g, only the first match is replaced.
Why does my regex test return true and then false?
A regex with the g or y flag keeps a lastIndex position between calls, so the next test starts where the previous one stopped. Remove the g flag for validation.
What is the difference between match and matchAll?
match with the g flag returns only the full matches as an array. matchAll returns an iterator of every match including capture groups and positions.
How do I use a variable in a JavaScript regex?
Build it with new RegExp and the string, escaping special characters in the variable first. Remember to double backslashes inside normal string literals.
What is catastrophic backtracking?
It is exponential slowdown caused by patterns with nested quantifiers when a match fails. In our test a 27 character input took almost three seconds with the pattern a plus inside a repeated group.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.