JavaScript Regex Flags and Methods: test, exec, match, matchAll, replace, split and lastIndex
Every regex flag (g, i, m, s, u, v, y, d) and every method that uses regexes: test and exec, match vs matchAll, search, replace and replaceAll with $ patterns and replacer functions, split with captures, the stateful lastIndex trap with g and y, and match indices.
kvi5hnuCode Sprout team member7 min readOn this page
Article 80 covered how to write patterns. This article covers how to use them: the flags that change how a pattern behaves, and the string and RegExp methods that find, extract, replace and split text. It also explains lastIndex, the hidden state behind one of the most confusing regex bugs in JavaScript.
Flags
Flags go after the closing slash (/pattern/gi) or in the constructor's second argument (new RegExp("pattern", "gi")):
| Flag | Property | Effect |
|---|---|---|
g | global | find all matches, not just the first |
i | ignoreCase | case-insensitive matching |
m | multiline | ^ and $ match at line breaks too |
s | dotAll | . also matches newlines |
u | unicode | Unicode mode: code points, \p{...}, \u{...}, stricter syntax |
v | unicodeSets | upgraded Unicode mode with set operations (ES2024) |
y | sticky | match only exactly at lastIndex |
d | hasIndices | record start/end indices of groups (ES2022) |
const re = /\w+/giu;
console.log(re.flags, re.global, re.ignoreCase, re.multiline, re.source);
try {
new RegExp("x", "uv"); // u and v can't be combined
} catch (err) {
console.log(err.name);
}
giu true true false \w+
SyntaxError
i, m and s
const log = "Error: disk\nwarning: cpu\nERROR: fan";
console.log(log.match(/^error/gim)); // i: any case; m: ^ at each line
console.log(log.match(/cpu$/), log.match(/cpu$/m)[0]);
console.log(/disk.warning/.test(log), /disk.warning/s.test(log));
[ 'Error', 'ERROR' ]
null cpu
false true
Without m, $ matches only at the very end of the input, so cpu$ fails. Without s, . stops at the newline. A portable "any character including newline" is [^] or [\s\S], which you'll see in older code.
i uses simple case folding, and only u or v mode handles some Unicode special cases: the long s ſ matches /s/iu but not /s/i.
u and v
Use u (or the newer v) for any pattern that deals with non-ASCII text. They make . and classes work with whole code points (so an emoji is one character), enable \p{...} property escapes, and turn some sloppy syntax (like useless escapes \- outside classes) into errors that catch mistakes.
The v flag (ES2024) adds set operations inside classes and properties of whole strings like emoji sequences:
console.log(/[\p{L}--[a-z]]/v.test("é"), /[\p{L}--[a-z]]/v.test("e")); // letters minus a-z
console.log(/[[a-z]&&[aeiou]]/v.test("e"), /[[a-z]&&[aeiou]]/v.test("b")); // intersection
console.log(/^\p{RGI_Emoji}$/v.test("👍🏽"), /^.$/u.test("👍🏽")); // one emoji, several code points
true false
true false
true false
-- subtracts one class from another, && intersects them, and \p{RGI_Emoji} matches complete emoji including skin-tone and family sequences. For new code, prefer v over u.
test(): does it match?
regex.test(string) returns a boolean. It's the right method for validation and conditions:
const isHexColor = /^#(?:[0-9a-f]{3}){1,2}$/i;
console.log(["#fff", "#C0FFEE", "#12345", "red"].map((c) => isHexColor.test(c)));
[ true, true, false, false ]
lastIndex: the stateful trap
A regex with the g or y flag is stateful. Its lastIndex property records where the previous match ended, and test() and exec() start searching from there:
const hasO = /o/g;
console.log(hasO.test("foo"), hasO.lastIndex);
console.log(hasO.test("foo"), hasO.lastIndex);
console.log(hasO.test("foo"), hasO.lastIndex); // no more matches: false, reset to 0
const startsWithA = /^a/g;
console.log(["apple", "avocado", "apricot"].filter((w) => startsWithA.test(w)));
true 2
true 3
false 0
[ 'apple', 'apricot' ]
"avocado" was rejected because the search started at index 5 (left over from "apple"), where ^a can't match. The rule: don't use g with test() unless you mean to step through matches, and don't share one g regex between unrelated strings. When a search fails, lastIndex resets to 0, which is why "apricot" passes again.

exec(): one match with details
regex.exec(string) returns a match array (or null) with the full match at [0], groups at [1], [2]..., plus index, input and groups:
const range = /(\d+)-(\d+)/g;
const text = "1-2 30-40";
let m;
while ((m = range.exec(text)) !== null) {
console.log(m[0], "from", m[1], "to", m[2], "at", m.index, "next search at", range.lastIndex);
}
1-2 from 1 to 2 at 0 next search at 3
30-40 from 30 to 40 at 4 next search at 9
That loop was the classic way to visit every match with its groups. matchAll (below) does the same thing more safely. Without g (or y), exec always searches from the start and returns the first match.
String methods that take regexes
search(): where is the first match?
console.log("Order #4521".search(/\d/), "no digits".search(/\d/));
7 -1
Like indexOf, but with a pattern. It ignores g and lastIndex.
match(): first match or all matches
match behaves very differently depending on the g flag:
const s = "a1 b22 c333";
const first = s.match(/[a-z](\d+)/);
console.log(first[0], first[1], first.index); // like exec: details and groups
console.log(s.match(/[a-z](\d+)/g)); // all full matches, no groups
console.log("abc".match(/\d/g)); // no match: null, not []
a1 1 0
[ 'a1', 'b22', 'c333' ]
null
With g, you get a plain array of matched strings and lose the groups and positions. And no match gives null, so str.match(re).length throws on non-matching input; write (str.match(re) ?? []).length or str.match(re)?.length ?? 0.
matchAll(): every match with details
matchAll returns an iterator of full match objects (groups, index, named groups) for every match. The regex must have the g flag:
const config = "host=example.org port=8080 debug=true";
for (const m of config.matchAll(/(?<key>\w+)=(?<value>\S+)/g)) {
console.log(m.index, m.groups.key, "->", m.groups.value);
}
const settings = Object.fromEntries(
Array.from(config.matchAll(/(\w+)=(\S+)/g), ([, key, value]) => [key, value]),
);
console.log(settings);
try {
"x".matchAll(/x/);
} catch (err) {
console.log(err.name);
}
0 host -> example.org
17 port -> 8080
27 debug -> true
{ host: 'example.org', port: '8080', debug: 'true' }
TypeError
matchAll works on an internal copy of the regex, so it doesn't disturb the original's lastIndex. For "find every match and its groups", it's the modern answer.
replace() and replaceAll()
replace(pattern, replacement) replaces the first match, or all matches if the regex has g. replaceAll requires g with a regex (it throws a TypeError otherwise), which makes the intent explicit.
The replacement string can refer to the match:
| Pattern | Inserts |
|---|---|
$& | the whole match |
$1, $2... | numbered groups |
$<name> | a named group |
$` / $' | the text before / after the match |
$$ | a literal $ |
console.log("Smith, Ana".replace(/(\w+), (\w+)/, "$2 $1"));
console.log("Total: 5".replace(/\d+/, "$$$&.00"));
console.log("2026-11-18".replace(/(?<y>\d+)-(?<m>\d+)-(?<d>\d+)/, "$<d>/$<m>/$<y>"));
console.log("a-b-c".replaceAll(/-/g, " + "));
Ana Smith
Total: $5.00
18/11/2026
a + b + c
Replacer functions
When the replacement needs logic, pass a function. It's called for each match with the match, then each group, then the offset and the whole string (and a groups object last, if the regex has named groups); its return value is inserted:
console.log("3 apples and 5 pears".replace(/\d+/g, (n) => n * 2));
console.log("snake_case_to_camel".replace(/_(\w)/g, (_, letter) => letter.toUpperCase()));
const prices = { apple: 1.2, pear: 0.8 };
const template = "apple: {apple}, pear: {pear}, plum: {plum}";
console.log(template.replace(/\{(\w+)\}/g, (whole, key) => prices[key] ?? whole));
6 apples and 10 pears
snakeCaseToCamel
apple: 1.2, pear: 0.8, plum: {plum}
The function receives the raw text, so $ characters in its return value are inserted literally, which makes functions the safe choice when replacement text comes from users.
split()
split accepts a regex separator. Captured groups in the separator are included in the result:
console.log("a, b;c d".split(/[,;\s]+/));
console.log("10+20-5".split(/([+-])/));
console.log("one two".split(/\s+/, 1));
[ 'a', 'b', 'c', 'd' ]
[ '10', '+', '20', '-', '5' ]
[ 'one' ]
Sticky matching with y
The y flag matches only at exactly lastIndex, without searching ahead. That's what you want when writing a tokenizer, where each token must start exactly where the previous one ended:
function tokenize(source) {
const token = /\s*(\d+|[-+*\/()])/y;
const tokens = [];
let m;
while ((m = token.exec(source)) !== null) tokens.push(m[1]);
if (token.lastIndex !== 0 || tokens.join("").length < source.replace(/\s/g, "").length) {
throw new SyntaxError(`Unexpected input after "${tokens.join(" ")}"`);
}
return tokens;
}
console.log(tokenize("12 + 3*(4 - 1)"));
try {
tokenize("2 + x");
} catch (err) {
console.log(err.name, err.message);
}
[
'12', '+', '3',
'*', '(', '4',
'-', '1', ')'
]
SyntaxError Unexpected input after "2 +"
With g instead of y, exec would skip over the invalid "x" silently and keep finding tokens later in the string.
Match indices with d
The d flag adds an indices array of [start, end] pairs for the match and each group, which is useful for highlighting matches in an editor:
const m = /(?<word>wor)ld/d.exec("hello world");
console.log(m.indices[0], m.indices[1], m.indices.groups.word);
[ 6, 11 ] [ 6, 9 ] [ 6, 9 ]
Which method should I use?
| Goal | Method |
|---|---|
| Does it match? | regex.test(str) (without g) |
| Position of the first match | str.search(regex) |
| First match with groups | str.match(regex) (no g) or regex.exec(str) |
| All matched strings | str.match(regex) with g (beware null) |
| All matches with groups and positions | str.matchAll(regex) with g |
| Replace | str.replace / str.replaceAll, with $ patterns or a function |
| Split on a pattern | str.split(regex) |
| Tokenizing | regex.exec with the y flag |
Common questions
Why does my regex test() alternate between true and false?
It has the g (or y) flag, so lastIndex carries over between calls. Remove g for plain testing, create the regex inside the function, or reset regex.lastIndex = 0 before each use.
How do I get all matches their capture groups?
Use str.matchAll(/.../g) and loop over the results, or Array.from(str.matchAll(re)). match with g returns only the matched strings.
How do I replace all occurrences of a plain string that contains special characters?
Use str.replaceAll(search, replacement) with a string, not a regex: string patterns are matched literally. If you need a regex (for example, case-insensitive), escape it with RegExp.escape(search).
Should I use u or v?
Use v in new code that targets current environments; it includes everything u does plus set operations and string properties. Some escapes inside classes are stricter in v mode, so existing u patterns occasionally need small changes.
Summary
- Flags:
gall matches,iignore case,mline anchors,sdot matches newline,u/vUnicode modes (vadds class set operations),ysticky,dindices. testanswers yes/no;execreturns detailed matches;searchgives the first position.matchwithoutgreturns details for the first match; withgreturns strings only; no match isnull.matchAll(requiresg) gives every match with groups and positions.replace/replaceAllsupport$&,$1,$<name>,$$and replacer functions;replaceAllwith a regex needsg.splitaccepts regex separators and includes captured separators.gandyregexes keeplastIndexstate; reusing them withtestcauses intermittent bugs.
Practice Questions
What does this print?
const re = /\d/g;
console.log(re.test("a1b2"), re.test("a1b2"), re.test("a1b2"));
Answer
true true false. The first test finds "1" (lastIndex 2), the second finds "2" (lastIndex 4), the third finds nothing and resets lastIndex to 0.
Convert "first_name, last_name" to "firstName, lastName" with one replace.
Answer
s.replace(/_([a-z])/g, (_, ch) => ch.toUpperCase())
What do "a1b2".match(/\d/) and "a1b2".match(/\d/g) return?
Answer
The first returns a match array for "1" with index: 1 and input; the second returns [ '1', '2' ] with no extra details.
Extract every {{placeholder}} name from a template like this one:
"Hi {{name}}, your code is {{code}}"
Answer
[...tpl.matchAll(/\{\{(\w+)\}\}/g)].map((m) => m[1])
Gives [ 'name', 'code' ].
Previous: JavaScript Regular Expressions: Literals, Character Classes, Quantifiers, Anchors and Groups

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.