Regex in JavaScript

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…

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

Two ways to escape a user's input:

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
}

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 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']

⚠️ What often goes wrong once a regex is in JavaScript code

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.

What you will learn