Mrs. Ratna has one tart cutter. There's one cutter; what changes is the hand movement: check whether the dough is enough for one cookie, cut one cookie, cut them all at once and note where each came from, change the shape, or cut the dough apart.
A regex in JavaScript works the same way. The pattern is one object (RegExp), and each movement is one method: check whether there's a match (test()), take one (match(), exec()), take them all with their positions (matchAll()), replace (replace()), or cut (split()). This lesson sums up those movements on the PO chat, plus two flags that change how a regex runs: g and y.
Making a regex: a literal and new RegExp()
const literal = /PO-\d{4}/g; // the pattern between two slashes, flags after
const fromString = new RegExp("PO-\\d{4}", "g"); // the pattern from a string
console.log(literal.source, fromString.source); // 'PO-\d{4}' 'PO-\d{4}'
const forgot = new RegExp("PO-\d{4}");
console.log(forgot.source); // 'PO-d{4}'
console.log(forgot.test(chat)); // false
console.log(new RegExp(String.raw`PO-\d{4}`).test(chat)); // true
- The literal
/pattern/flagsis for a pattern you already know when you write the code. Flags come after the closing slash, like/tart/gi. new RegExp(text, flags)is for a pattern that only exists while the program runs, such as from a variable or a user's input.- In a normal string, JavaScript uses the backslash itself.
"\d"becomes"d", so the pattern turns intoPO-d{4}: "PO-, then the letter d four times". Nothing in the chat matches, sofalse, even thoughPO-0412is right there. Write"\\d", or useString.raw, which leaves backslashes as they are."\b"is worse: in a string it becomes the backspace character. - A user's input in
new RegExp()must be escaped first:word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"). Without it,"85.00"also matches85x00, and"(tart"throwsSyntaxError: Invalid regular expression: /(tart/: Unterminated group. There is a shorter way,RegExp.escape(), below.
Two ways to escape a user's input:
RegExp.escape(word): the default for new code, because it can't forget a character. According to MDN, it has been Baseline since May 2025: Chrome 136, Firefox 134, Safari 18.2 and Node 24.new RegExp(RegExp.escape("85.00")).test("85x00")givesfalse. Don't be surprised when its.sourceis\x385\.00: the first letter or digit is written as the code\x38(the digit8), so it can't merge with an escape in front of it. The pattern still matches85.00.word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"): when your code must also run on Node 22 or older browsers, which don't haveRegExp.escapeyet.
test(), match() and matchAll()
console.log(/PO-\d{4}/.test(chat)); // true
console.log(chat.match(/PO-(\d{4})/)[1]); // '0412'
console.log(chat.match(/PO-(\d{4})/).index); // 126
console.log(chat.match(/PO-(\d{4})/g)); // ['PO-0412', 'PO-0413']
console.log("abc123def456".match(/\d+/g)); // ['123', '456']
for (const m of chat.matchAll(/PO-(\d{4})/g)) {
console.log(m[0], m[1], m.index); // 'PO-0412' '0412' 126, then 'PO-0413' '0413' 585
}
test()only answerstrueorfalse. It fits validation best.match()withoutg: the first match, with its groups andindex. Nothing matches:null.match()withg: every match, but only its text. The groups andindexare gone.matchAll()gives every match complete with its groups andindex. It requiresg; withoutgit throwsTypeError: String.prototype.matchAll called with a non-global RegExp argument. The result is an iterator: usefor...of, or[...chat.matchAll(pattern)]for an array.search()gives the index of the first match, or-1:"PO-0412".search(/\d/)gives3.
exec(), lastIndex and the y flag
A regex with the g flag (or y) remembers where it stopped, in the lastIndex property. test() and exec() carry on from there.
const re = /PO-(\d{4})/g;
console.log(re.test(chat), re.lastIndex); // true 133
console.log(re.test(chat), re.lastIndex); // true 592
console.log(re.test(chat), re.lastIndex); // false 0
const finder = /PO-(\d{4})/g;
let m;
while ((m = finder.exec(chat)) !== null) {
console.log(m[1], finder.lastIndex); // '0412' 133, then '0413' 592
}
- The third call fails because there's no more
PO-after position 592, thenlastIndexgoes back to 0. Same regex, same text, different result: the classic bug when agregex is reused fortest(). - The
exec()loop uses that behaviour on purpose: each call gives the next match, untilnull.
The y flag (sticky) is stricter: it only tries exactly at lastIndex and doesn't search ahead.
const sticky = /PO-\d{4}/y;
console.log(sticky.test(chat)); // false position 0 holds '['
sticky.lastIndex = 126;
console.log(sticky.test(chat)); // true
The y flag is used by programs that read a text piece by piece from the left, like parsers.
replace() and split()
console.log("Hello World".replace(/world/i, "Regex")); // 'Hello Regex'
console.log("07700-900-123".replace(/-/, "")); // '07700900-123'
console.log("07700-900-123".replace(/-/g, "")); // '07700900123'
console.log("on 25/03".replace(/(\d{2})\/(\d{2})/, "$2-$1")); // 'on 03-25'
const prices = chat.replace(/(\d+) (?:dollars|bucks)\b/g, (_, amount) => "$" + amount);
console.log(prices.split("\n")[4]); // '[12/03/26 07.25] Sari: TART 3 jars = $255 right? ...'
console.log("+44 7700-900-456".split(/[- ]/)); // ['+44', '7700', '900', '456']
console.log("07700-900-123".split(/(-)/)); // ['07700', '-', '900', '-', '123']
- Without
g,replace()only replaces the first match. Withg, all of them. Theiflag makesworldmatchWorld. - The replacement can use what the groups hold:
$1,$2, or$<name>. - The replacement can also be a function. It receives the whole match, then each group's text, and what it
returns becomes the replacement. Here255 dollarsbecomes$255. split()with a regex cuts at every separator that matches. A group in the separator pattern is kept in the result.replaceAll()with a regex also requiresg; otherwise:TypeError: String.prototype.replaceAll called with a non-global RegExp argument.
⚠️ What often goes wrong once a regex is in JavaScript code
- The backslash disappears in a string.
new RegExp("\d+")is the same as/d+/. Write"\\d+"or useString.raw. - A
gregex reused fortest(). ItslastIndexcarries over, so the results alternate. For validation, don't useg, or setre.lastIndex = 0first. match()withgdrops the groups. Need each match's groups?matchAll().replace()withoutgonly replaces the first one.- A user's input going into
new RegExp()unescaped. A dot becomes "any character", and an unfinished parenthesis throws a SyntaxError.
TL;DR: A regex literal is written /pattern/flags; new RegExp("text", "flags") is for dynamic patterns, with backslashes doubled ("\\d") or through String.raw, and a user's input escaped first. test() answers true/false. match() without g gives the first match with its groups; with g it gives every text without groups, for example "abc123def456".match(/\d+/g) gives ["123", "456"]. matchAll() (requires g) gives everything complete. A regex with g or y keeps lastIndex, so test() and exec() carry on from the last position; y only tries exactly at that position. replace() replaces the first match, or all with g, and takes $1, $<name> or a function: "Hello World".replace(/world/i, "Regex") gives "Hello Regex". split() cuts at every separator that matches.
⚡ One pattern, many movements
Write:
console.log(/PO-\d{4}/.test(chat)); // true
console.log(chat.match(/PO-(\d{4})/g)); // ['PO-0412', 'PO-0413']
console.log("abc123def456".match(/\d+/g)); // ['123', '456']
Meaning: test() answers true or false. match() without g gives the first match with its groups and index; with g it gives every matching text, without groups. matchAll() (which requires g) gives every match complete.
⚡ A pattern from a string
Write:
const forgot = new RegExp("PO-\d{4}");
console.log(forgot.test(chat));
Guess first: PO-0412 is right there in the chat. Is the result true or false?
false. In a normal string "\d" becomes "d", so the pattern is PO-d{4}. Write "\\d", or use String.raw.
Meaning: new RegExp() is for a pattern that only exists while the program runs. Double its backslashes, and escape a user's input before it goes in.
⚡ g remembers where it stopped
Write:
const re = /PO-(\d{4})/g;
console.log(re.test(chat), re.lastIndex); // true 133
console.log(re.test(chat), re.lastIndex); // true 592
console.log(re.test(chat), re.lastIndex); // false 0
Meaning: A regex with g keeps lastIndex, and test() carries on from there. Same regex, same text, different result: for validation, leave g off.