Regular expressions
suggest changeNode.js uses the regular expression engine of V8, so everything here is standard JavaScript: the RegExp class, regex literals like /\d+/g, and string methods such as match(), matchAll(), replace() and split(). Node.js 24 (V8 13.6) also supports the newer additions: named groups (including duplicate names), lookbehind, the d, s, u and v flags, inline modifiers like (?i:...) and RegExp.escape().
The examples were run with Node.js 24 as ES modules (.mjs files).
Creating a regular expression
There are two ways to create a regex: a literal, which is compiled once when the script is parsed, and the RegExp constructor, which builds one from a string at runtime:
const literal = /\d{4}-\d{2}-\d{2}/;
const fromString = new RegExp('\\d{4}-\\d{2}-\\d{2}');
console.log(literal.source === fromString.source);
console.log(literal.test('released 2026-10-17'));
const word = 'cat';
const re = new RegExp(`\\b${word}s?\\b`, 'gi');
console.log(re);
console.log('Cats and a cat, but not a catalog'.match(re));
true
true
/\bcats?\b/gi
[ 'Cats', 'cat' ]
Use a literal when the pattern is fixed. In a string passed to new RegExp() every backslash has to be doubled, because '\d' in a JavaScript string is just d. String.raw avoids that: new RegExp(String.raw`\d+`).
Escaping user input
When part of the pattern comes from the user, characters like ., $, ( and ? are interpreted as regex syntax. That produces wrong matches at best and a SyntaxError (or a slow pattern, see below) at worst. RegExp.escape() (new in Node.js 24) escapes a string so it matches literally:
const userInput = 'price: $5.00 (approx.)';
const naive = new RegExp(userInput);
console.log(naive.test(userInput));
const safe = new RegExp(RegExp.escape(userInput));
console.log(safe.source);
console.log(safe.test(userInput));
false
\x70rice\x3a\x20\$5\.00\x20\(approx\.\)
true
The output looks odd because RegExp.escape() also escapes a leading letter or digit and characters like spaces and : as \xNN, so the result is safe to concatenate in any position. On older Node.js versions use the classic replacement: s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').
Flags
Flags come after the closing slash of a literal or as the second argument to new RegExp():
| Flag | Property | Meaning |
|---|---|---|
g |
global |
find all matches; makes the regex stateful (lastIndex) |
i |
ignoreCase |
case-insensitive |
m |
multiline |
^ and $ match at line breaks, not just at the start and end of input |
s |
dotAll |
. also matches \n |
u |
unicode |
treat the pattern and input as code points, enable \p{...} |
v |
unicodeSets |
u plus set operations and string properties in classes |
y |
sticky |
match only at exactly lastIndex |
d |
hasIndices |
record start and end positions of every group |
m and s are often confused. m changes what ^ and $ mean, s changes what . means:
const text = 'first line\nsecond line\nthird line';
console.log(text.match(/^\w+/g));
console.log(text.match(/^\w+/gm));
console.log(/first.*second/.test(text));
console.log(/first.*second/s.test(text));
[ 'first' ]
[ 'first', 'second', 'third' ]
false
true
Testing and finding matches
The methods you'll use most are regex.test() for a yes/no answer, str.match() and str.matchAll() for extracting matches, and str.search() for the position of the first match:
const text = 'Order 1042 shipped on 2026-10-17, order 1043 on 2026-10-19.';
console.log(/\d+/.test(text));
console.log(text.search(/\d{4}-/));
const first = text.match(/order (\d+)/i);
console.log(first[0], first[1], first.index);
console.log(text.match(/\d{4}-\d{2}-\d{2}/g));
console.log(text.match(/invoice/g));
for (const m of text.matchAll(/order (\d+)/gi)) {
console.log(`${m[1]} at ${m.index}`);
}
true
22
Order 1042 1042 0
[ '2026-10-17', '2026-10-19' ]
null
1042 at 0
1043 at 34
match() behaves very differently depending on the g flag:
- without
git returns the first match with its capture groups,indexandgroups(the same asregex.exec(str)) - with
git returns an array of the whole matched strings only, with no groups and no positions - if nothing matches, it returns
null, not an empty array; writestr.match(re) ?? []when you want to iterate
matchAll() gives you both: every match with all its groups. It requires the g flag and throws a TypeError without it.
Capture groups
Parentheses create numbered groups. (?<name>...) creates a named group, which is much easier to read than m[3]. Use (?:...) when you only need grouping (for | or a quantifier) without capturing:
const line = '2026-10-17T09:15:02Z ERROR [db] connection refused';
const re = /^(?<date>[\d-]+)T(?<time>[\d:]+)Z (?<level>[A-Z]+) \[(?<module>\w+)\] (?<message>.*)$/;
const m = line.match(re);
console.log(m.groups);
const { level, module: mod } = m.groups;
console.log(`${level} in ${mod}`);
const [whole, day] = '2026-10-17'.match(/(?:\d+-)+(\d+)/);
console.log(whole, day);
console.log(/(\d+)(?:px|em)/.exec('width: 12em').slice(1));
[Object: null prototype] {
date: '2026-10-17',
time: '09:15:02',
level: 'ERROR',
module: 'db',
message: 'connection refused'
}
ERROR in db
2026-10-17 17
[ '12' ]
m.groups is an object with a null prototype, so destructuring works but it has no toString() or hasOwnProperty() methods. A group that didn't participate in the match is undefined.
The same name can be used in different alternatives, which is handy for accepting several input formats:
const date = /(?<year>\d{4})-(?<month>\d{2})|(?<month>\d{2})\/(?<year>\d{4})/;
for (const s of ['2026-10', '10/2026']) {
const { year, month } = s.match(date).groups;
console.log(year, month);
}
2026 10
2026 10
Backreferences and match positions
Inside a pattern, \1 or \k<name> matches the same text that the group matched. The d flag adds an indices array with [start, end] for every group:
console.log('this is is a test test'.match(/\b(\w+) \1\b/g));
console.log(/(?<q>['"]).*?\k<q>/.exec(`say "it's fine" now`)[0]);
const m = /(?<key>\w+)=(?<value>\w+)/d.exec(' color=blue');
console.log(m.indices[0], m.indices.groups.key, m.indices.groups.value);
[ 'is is', 'test test' ]
"it's fine"
[ 2, 12 ] [ 2, 7 ] [ 8, 12 ]
Positions are useful for highlighting matches or reporting errors at a column in the input.
Replacing
str.replace(re, replacement) replaces the first match, or all matches if the regex has the g flag. str.replaceAll(re, replacement) requires the g flag and throws without it, which protects you from accidentally replacing only the first occurrence.
The replacement string can refer to the match:
| Pattern | Inserts |
|---|---|
$& |
the whole match |
$1, $2, ... |
numbered group |
$<name> |
named group |
$` / $' |
text before / after the match |
$$ |
a literal $ |
const dates = 'from 2026-10-17 to 2026-12-31';
console.log(dates.replace(/(\d{4})-(\d{2})-(\d{2})/g, '$3.$2.$1'));
console.log(dates.replace(/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/g, '$<m>/$<d>/$<y>'));
console.log('cost: 5'.replace(/\d+/, '$$$&.00'));
console.log('a-b-c'.replace(/-/, '+'));
console.log('a-b-c'.replace(/-/g, '+'));
try {
'a-b-c'.replaceAll(/-/, '+');
} catch (err) {
console.log(err.constructor.name, err.message);
}
from 17.10.2026 to 31.12.2026
from 10/17/2026 to 12/31/2026
cost: $5.00
a+b-c
a+b+c
TypeError String.prototype.replaceAll called with a non-global RegExp argument
For anything more complex, pass a function. It's called for every match with the match, each group, the offset, the whole string and, if the regex has named groups, the groups object as the last argument. Its return value is used as the replacement:
const template = 'Hello {name}, you have {count} new {unknown}.';
const values = { name: 'Ada', count: 3 };
const out = template.replace(/\{(\w+)\}/g, (match, key) =>
key in values ? String(values[key]) : match
);
console.log(out);
const prices = 'apple 1.20, pear 0.90';
console.log(prices.replace(/\d+\.\d+/g, (p) => (Number(p) * 1.1).toFixed(2)));
const toCamel = (s) => s.replace(/[-_](\w)/g, (_, c) => c.toUpperCase());
const toKebab = (s) => s.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase());
console.log(toCamel('background-color'), toCamel('max_retry_count'));
console.log(toKebab('backgroundColor'));
Hello Ada, you have 3 new {unknown}.
apple 1.32, pear 0.99
backgroundColor maxRetryCount
background-color
A function replacement is also the safe choice when the replacement text comes from outside: a user-supplied string containing $& or $1 would otherwise be interpreted.
Splitting
str.split() accepts a regex, which handles inconsistent separators. Capture groups in the separator are included in the result:
console.log('a, b;c ; d'.split(/\s*[,;]\s*/));
console.log('one two\tthree\nfour'.split(/\s+/));
console.log('1+2-3'.split(/([+-])/));
const csvLine = 'name, , age ,';
console.log(csvLine.split(/\s*,\s*/));
console.log(' padded words '.trim().split(/\s+/));
[ 'a', 'b', 'c', 'd' ]
[ 'one', 'two', 'three', 'four' ]
[ '1', '+', '2', '-', '3' ]
[ 'name', '', 'age', '' ]
[ 'padded', 'words' ]
Splitting ' x' on /\s+/ gives a leading empty string, which is why the last example calls trim() first.
The lastIndex trap
A regex with the g or y flag remembers where the last match ended in its lastIndex property, and test() and exec() start searching from there. Reusing such a regex for different strings gives surprising results:
const isDigits = /^\d+$/g;
console.log(isDigits.test('123'), isDigits.lastIndex);
console.log(isDigits.test('456'), isDigits.lastIndex);
console.log(isDigits.test('789'), isDigits.lastIndex);
const ids = ['42', '43', '44', '45'];
console.log(ids.filter((s) => isDigits.test(s)));
true 3
false 0
true 3
[ '43', '45' ]
The second call starts at position 3 of '456', fails, and resets lastIndex to 0, so every other string is rejected. The fix is simple: don't use g with test(). You need g only for matchAll(), replace()/replaceAll() of all matches, match() returning all matches, or a manual exec() loop. The string methods (match, matchAll, replace, split) reset or copy lastIndex themselves, so they're not affected.
The manual loop is how all matches were collected before matchAll():
const re = /\$(\d+)/g;
const s = 'pay $10, then $25, then $5';
let m;
while ((m = re.exec(s)) !== null) {
console.log(m[1], 'next search starts at', re.lastIndex);
}
10 next search starts at 7
25 next search starts at 17
5 next search starts at 26
Be careful with patterns that can match an empty string (like /x*/g): exec() doesn't advance lastIndex after an empty match, so such a loop never ends. matchAll() handles this for you.
Sticky matching: a tiny tokenizer
The y flag anchors the match at lastIndex: the regex must match right there or fail, instead of searching ahead. Together with named groups that makes a compact tokenizer, where any unexpected character is reported instead of being silently skipped:
function tokenize(input) {
const re = /\s*(?:(?<num>\d+(?:\.\d+)?)|(?<id>[a-z_]\w*)|(?<op>[-+*\/()=]))/iy;
const tokens = [];
re.lastIndex = 0;
while (re.lastIndex < input.length) {
const start = re.lastIndex;
const m = re.exec(input);
if (!m) {
const offset = input.slice(start).search(/\S/);
if (offset === -1) break; // only trailing whitespace left
const pos = start + offset;
throw new SyntaxError(`unexpected '${input[pos]}' at position ${pos}`);
}
const [type, value] = Object.entries(m.groups).find(([, v]) => v !== undefined);
tokens.push(`${type}:${value}`);
}
return tokens;
}
console.log(tokenize('total = price * 1.08 + (tax - 2)'));
try {
tokenize('a = b # c');
} catch (err) {
console.log(err.message);
}
[
'id:total', 'op:=',
'id:price', 'op:*',
'num:1.08', 'op:+',
'op:(', 'id:tax',
'op:-', 'num:2',
'op:)'
]
unexpected '#' at position 6
Without y the regex would find the next token anywhere after the # and the error would go unnoticed.
Lookahead and lookbehind
Lookarounds check what comes before or after a position without including it in the match:
| Syntax | Name | Matches if... |
|---|---|---|
X(?=Y) |
lookahead | X is followed by Y |
X(?!Y) |
negative lookahead | X is not followed by Y |
(?<=Y)X |
lookbehind | X is preceded by Y |
(?<!Y)X |
negative lookbehind | X is not preceded by Y |
console.log('USD 100, EUR 200, USD 300'.match(/(?<=USD )\d+/g));
console.log('price: 100kg 200 300kg'.match(/\b\d+(?!\d|kg)\b/g));
const addCommas = (n) => String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
console.log(addCommas(1234567), addCommas(999));
const strong = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{10,}$/;
for (const pw of ['password', 'Passw0rd', 'CorrectHorse9']) {
console.log(pw, strong.test(pw));
}
[ '100', '300' ]
[ '200' ]
1,234,567 999
password false
Passw0rd false
CorrectHorse9 true
The password check uses one lookahead per requirement because they all start from position 0; this keeps the rules independent of order. In real code, separate checks with clear error messages are often better for users. And for formatting numbers, Intl.NumberFormat or n.toLocaleString('en-US') is the right tool; the regex is shown because the technique is common.
Inline modifiers
(?i:...) turns on a flag for part of the pattern, and (?-i:...) turns it off. Supported flags are i, m and s:
const re = /^(?i:content-type): (?-i:text\/html)/;
console.log(re.test('Content-Type: text/html'));
console.log(re.test('CONTENT-TYPE: text/html'));
console.log(re.test('content-type: TEXT/HTML'));
true
true
false
This is useful when a pattern is built from parts that need different rules, for example a case-insensitive header name with a case-sensitive value.
Unicode: the u and v flags
Without a Unicode flag, a regex works on UTF-16 code units, so characters outside the Basic Multilingual Plane (most emoji, some CJK characters) count as two "characters". The u flag makes the regex operate on code points and enables Unicode property escapes like \p{L} (any letter) and \p{Script=Greek}:
const s = 'naïve café 😀';
console.log(s.match(/\w+/g));
console.log(s.match(/\p{L}+/gu));
console.log(/^.$/.test('😀'), /^.$/u.test('😀'));
console.log('Ελληνικά and English'.match(/\p{Script=Greek}+/gu));
[ 'na', 've', 'caf' ]
[ 'naïve', 'café' ]
false true
[ 'Ελληνικά' ]
\w, \d and \b stay ASCII-only even with u, which is why \w+ breaks words at ï and é. Use \p{L}, \p{N} and friends for international text.
The v flag (Node.js 20+) is an upgraded u. It adds set subtraction (--) and intersection (&&) inside character classes and properties of strings like \p{RGI_Emoji}, which match multi-code-point emoji as a whole:
const consonants = /[[a-z]--[aeiou]]/gv;
console.log('regular expressions'.match(consonants).join(''));
const greekLetters = /[\p{Script=Greek}&&\p{L}]+/gv;
console.log('π = 3.14, Ω!'.match(greekLetters));
console.log('ok 👍🏽 👨👩👧'.match(/\p{RGI_Emoji}/gv));
rglrxprssns
[ 'π', 'Ω' ]
[ '👍🏽', '👨👩👧' ]
The v flag is stricter about syntax: characters like (, ), [, {, /, - and | must be escaped inside a class. You can't combine u and v. Unicode normalization, case folding and encodings in general are a broader topic; regexes don't normalize, so é written as one code point doesn't match é written as e plus a combining accent unless you call str.normalize() on both first.
Catastrophic backtracking (ReDoS)
V8 uses a backtracking engine. For most patterns that's fast, but nested quantifiers that can match the same text in many ways, like (a+)+, (\w+\s?)* or (a|aa)*, take exponential time when the input almost matches. Because JavaScript is single-threaded, one such regex blocks the event loop and freezes the whole server. This is called ReDoS (regular expression denial of service):
const evil = /^(a+)+$/;
evil.test('a!'); // warm up: V8 compiles a regex to machine code after its first use
for (const n of [20, 22, 24, 26, 28]) {
const input = 'a'.repeat(n) + '!';
const start = performance.now();
evil.test(input);
console.log(n, `${(performance.now() - start).toFixed(1)} ms`);
}
20 9.8 ms
22 42.1 ms
24 178.1 ms
26 626.9 ms
28 2504.7 ms
Every two extra characters make it roughly three to four times slower; 40 characters would take hours. The equivalent /^a+$/ answers instantly. Ways to protect yourself:
- Avoid nested quantifiers over overlapping patterns.
(\w+\s?)*can usually be written as\w+(?:\s\w+)*, where each character can only be matched one way. - Limit input length before matching (
if (s.length > 1000) reject()). It's the cheapest defense. - Never build regexes from user input without
RegExp.escape(). - For patterns supplied by users, use the
re2package, a binding to Google's RE2 engine which guarantees linear time (it doesn't support backreferences and lookarounds). - Run untrusted patterns with a time limit.
vmscripts can be interrupted, even in the middle of a regex:
import vm from 'node:vm';
function safeTest(re, str, timeout = 50) {
try {
return vm.runInNewContext('re.test(str)', { re, str }, { timeout });
} catch (err) {
if (err.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT') return null;
throw err;
}
}
console.log(safeTest(/^(a+)+$/, 'aaaa'));
const start = performance.now();
console.log(safeTest(/^(a+)+$/, 'a'.repeat(40) + '!'));
console.log(`gave up after ${(performance.now() - start).toFixed(0)} ms`);
true
null
gave up after 51 ms
The timeout is enforced by V8 interrupting the script, so it still runs on the main thread for up to timeout milliseconds; for heavy use run it in a worker thread.
Practical patterns
A few patterns that come up often. Keep them anchored with ^ and $ when validating, otherwise /\d+/ happily accepts abc123xyz:
const patterns = {
uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
semver: /^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?:-(?<pre>[\w.-]+))?$/,
hexColor: /^#(?:[0-9a-f]{3}){1,2}$/i,
slug: /^[a-z0-9]+(?:-[a-z0-9]+)*$/,
};
console.log(patterns.uuid.test(crypto.randomUUID()));
console.log(patterns.semver.exec('24.20.0-rc.1').groups);
console.log(['#fff', '#a1b2c3', '#abcd'].map((c) => patterns.hexColor.test(c)));
console.log(['hello-world', 'Hello World', 'a--b'].map((s) => patterns.slug.test(s)));
const slugify = (title) =>
title
.normalize('NFKD')
.replace(/\p{M}/gu, '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '');
console.log(slugify(' Crème Brûlée: A How-To Guide! '));
true
[Object: null prototype] {
major: '24',
minor: '20',
patch: '0',
pre: 'rc.1'
}
[ true, true, false ]
[ true, false, false ]
creme-brulee-a-how-to-guide
Some things are better done without a regex:
- Email addresses: the full grammar is huge. Check for something like
/^[^\s@]+@[^\s@]+\.[^\s@]+$/and confirm by sending a mail. - URLs:
new URL(str)parses and validates them, andURL.canParse(str)returns a boolean. - HTML: use a real parser (see Web scraping).
- JSON, CSV, dates: use
JSON.parse(), a CSV library andDate/Intlparsing respectively. - Simple checks:
str.startsWith(),str.endsWith(),str.includes()are clearer and faster than/^foo/.
Processing a log file line by line
Regexes are often combined with readline to process big files without loading them into memory. This counts log levels and collects error messages per module:
import { createReadStream, writeFileSync } from 'node:fs';
import { createInterface } from 'node:readline';
writeFileSync('app.log', [
'2026-10-17T09:15:00Z INFO [http] GET /users 200',
'2026-10-17T09:15:01Z WARN [db] slow query 1250ms',
'2026-10-17T09:15:02Z ERROR [db] connection refused',
'garbage line',
'2026-10-17T09:15:04Z ERROR [auth] token expired',
'2026-10-17T09:15:05Z INFO [http] GET /health 200',
].join('\n'));
const lineRe = /^(?<ts>\S+) (?<level>INFO|WARN|ERROR) \[(?<mod>\w+)\] (?<msg>.*)$/;
const counts = {};
const errors = [];
let bad = 0;
const rl = createInterface({ input: createReadStream('app.log'), crlfDelay: Infinity });
for await (const line of rl) {
const m = lineRe.exec(line);
if (!m) { bad++; continue; }
const { level, mod, msg } = m.groups;
counts[level] = (counts[level] ?? 0) + 1;
if (level === 'ERROR') errors.push(`${mod}: ${msg}`);
}
console.log(counts);
console.log(errors);
console.log('unparsed lines:', bad);
{ INFO: 2, WARN: 1, ERROR: 2 }
[ 'db: connection refused', 'auth: token expired' ]
unparsed lines: 1
The regex is created once outside the loop and has no g flag, so exec() always starts at the beginning of each line.
Summary
- Prefer regex literals; with
new RegExp()double the backslashes or useString.raw, and escape user input withRegExp.escape(). match()withoutgreturns groups, withgonly strings; usematchAll()to get every match with groups. No match isnull.- Use named groups
(?<name>...)and$<name>/m.groups.nameinstead of counting parentheses. - Use a function as the replacement for computed or untrusted replacement text;
replaceAll()requiresg. - Don't use the
gflag withtest()on a shared regex:lastIndexmakes results alternate. ymatches only atlastIndex, which is what tokenizers need.\w,\dand\bare ASCII-only; use theuorvflag and\p{...}for international text.- Nested quantifiers can take exponential time and block the event loop. Limit input length, simplify patterns, and use
re2or avmtimeout for untrusted patterns.