Regex in JavaScript
JavaScript has regular expressions built into the language. You create a RegExp object and use it through a handful of String and RegExp methods. Knowing which method returns what — and how the g flag changes them — is most of the battle.
Creating a regex
const a = /\d+/g; // literal: compiled once, best for fixed patterns
const b = new RegExp("\\d+", "g"); // constructor: for patterns built at run time
const word = "cat";
const c = new RegExp(`\\b${word}s?\\b`, "i");
console.log(a.source, a.flags);
console.log(b.source === a.source);
console.log(c);\d+ g
true
/\bcats?\b/i
In a string, every backslash must be doubled ("\\d"), because the string literal consumes one level of escaping before RegExp sees it.
The methods at a glance
| Method | Returns | With g |
|---|---|---|
re.test(s) |
true / false |
advances re.lastIndex (see the pitfall below) |
s.search(re) |
index of first match or -1 |
ignores g |
s.match(re) |
first match with groups, or null |
array of all match strings (no groups) |
s.matchAll(re) |
iterator of match objects | g is required |
re.exec(s) |
next match object or null |
continues from lastIndex |
s.replace(re, r) |
new string | replaces all instead of first |
s.replaceAll(re, r) |
new string | g is required |
s.split(re) |
array of pieces | ignores g |
test and search
const email = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(email.test("lan@example.vn"), email.test("lan@"));
console.log("Order #4521 shipped".search(/\d/));true false
7
match vs matchAll
match without g gives you the first match with all its details. With g it gives only the matched strings. When you need every match and its groups, use matchAll:
const s = "x=1, y=22, z=333";
console.log(s.match(/(\w)=(\d+)/).slice(0, 3));
console.log(s.match(/(\w)=(\d+)/g));
for (const m of s.matchAll(/(?<key>\w)=(?<val>\d+)/g)) {
console.log(m.index, m.groups.key, m.groups.val);
}[ 'x=1', 'x', '1' ]
[ 'x=1', 'y=22', 'z=333' ]
0 x 1
5 y 22
11 z 333
The same matches in the tester:
/(?<key>\w)=(?<val>\d+)/g
x=1, y=22, z=3333 matches
#1 "x=1" at index 0
group key: "x"
group val: "1"
#2 "y=22" at index 5
group key: "y"
group val: "22"
#3 "z=333" at index 11
group key: "z"
group val: "333"
replace with strings and functions
const s = "John SMITH, mary jones";
const title = s.replace(/\b(\p{L})(\p{L}*)/gu, (_, first, rest) => first.toUpperCase() + rest.toLowerCase());
console.log(title);
console.log("2025-07-31".replace(/(?<y>\d+)-(?<m>\d+)-(?<d>\d+)/, "lt;d>/lt;m>/lt;y>"));
console.log("a.b.c".replaceAll(".", "/"));John Smith, Mary Jones
31/07/2025
a/b/c
Note the last line: with a string argument, replaceAll treats . literally — no escaping needed.
split
console.log("a, b;c ,d".split(/\s*[,;]\s*/));
console.log("2025-07-31T10:20".split(/[-T:]/));
console.log("one1two22three".split(/(\d+)/));[ 'a', 'b', 'c', 'd' ]
[ '2025', '07', '31', '10', '20' ]
[ 'one', '1', 'two', '22', 'three' ]
The lastIndex pitfall
A regex with g or y is stateful: test and exec remember where they stopped in lastIndex. Reusing such a regex across different strings gives confusing results:
const hasDigit = /\d/g;
console.log(hasDigit.test("a1"), hasDigit.lastIndex);
console.log(hasDigit.test("b2"), hasDigit.lastIndex);
console.log(hasDigit.test("b2"), hasDigit.lastIndex);true 2
false 0
true 2
The second call started searching "b2" at index 2 — past the digit — so it failed and reset lastIndex to 0. Fixes: don't use g with test, or reset re.lastIndex = 0, or use matchAll/match, which don't depend on the starting lastIndex.
A classic exec loop
Before matchAll existed, code looped with exec. You will still see this pattern:
const re = /\[(\w+)\]/g;
const text = "[info] start [warn] slow [error] boom";
let m;
while ((m = re.exec(text)) !== null) {
console.log(m[1], "at", m.index, "next search from", re.lastIndex);
}info at 0 next search from 6
warn at 13 next search from 19
error at 25 next search from 32
Test yourself
What does "a1b2".match(/\d/g) return?
['1']with index info['1', '2']1- An iterator
Why can re.test() give different answers for the same string?
- Regexes are random
- With
g/y,testcontinues fromlastIndex - Strings are mutable
- Because of the
iflag
Which method returns every match together with its groups?
matchwithgsearchmatchAllsplit