1. Home
  2. Blog
  3. Software Development

Software Development

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.

9 min read
JavaScript regex explained: patterns, flags, groups and pitfalls

Key takeaways

  • JavaScript regex literals look like /pattern/flags; use new RegExp() when the pattern is built at runtime.
  • Without the g flag, replace changes only the first match and match returns capture groups instead of all matches.
  • A global regex used with test() remembers lastIndex: 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
  • test returns a boolean: the right tool for validation.
  • match without g returns the first match with its capture groups and position; with g it returns all full matches but loses the groups.
  • matchAll (requires g) 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Software Development

Python Abstract Class: ABC, abstractmethod and When to Use Them

Python abstract class explained: ABC and abstractmethod, abstract properties, shared logic with super, register, collections.abc and ABC vs Protocol, tested.

Read article →
Software Development

Python Subprocess Explained: run, Capture Output, Timeouts and Safety

Python subprocess explained with tested examples: run, capture_output, check, timeouts, input, environment, shell injection, encoding on Windows and Popen streaming.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
Software Development

URL Query Parameters: Encoding, URLSearchParams and Common Traps

URL query parameters explained: reading and building them with URLSearchParams and urllib, percent encoding, plus signs, repeated keys and nine…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Software Development

JavaScript BigInt Explained: Big Numbers, Division and JSON

JavaScript BigInt explained: the 2^53 limit, creating and converting BigInt, division, mixing types, JSON stringify and parse without losing digits,…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Databases & SQL

Gaps and Islands in SQL: Find Streaks and Missing Ranges

Gaps and islands in SQL: find login streaks and missing ranges with ROW_NUMBER, DENSE_RANK, LAG and LEAD, plus the duplicate…

Read article →
Databases & SQL

INSERT INTO SELECT in SQL: Copy Rows Between Tables Safely

INSERT INTO SELECT in SQL: copy rows between tables with chosen columns, joins and summaries, avoid duplicates on reruns, upsert,…

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →
Artificial Intelligence

K Means Clustering Explained: How It Works, With Python Code

K means clustering explained: the algorithm, a from-scratch NumPy version, choosing k with the elbow and silhouette methods, k-means++, scaling…

Read article →
DevOps

Git Log Explained: 15 Useful Commands and Pretty Formats

Git log explained with 15 tested commands: oneline, graph, filters by author, date, message and code, file history, stats, pretty…

Read article →
Test Automation

Pytest conftest.py Explained: Shared Fixtures, Hooks and Overrides

Pytest conftest.py explained with a tested suite: shared fixtures, scope and teardown, folder overrides, autouse, custom options, markers and useful…

Read article →
Software Testing

Usability Testing: Methods, Metrics, SUS Score and Checklist

Usability testing explained: methods, planning, writing tasks, running sessions, metrics, SUS scoring, how many users you need and a practical…

Read article →