How do you tell a regex "take dollars or bucks"? And how do you check there's a $ in front of a number without taking the $ too?
Mrs. Ratna does both when she copies prices from the chat into her notebook. Prices are written 90 dollars or 75 bucks, and she takes both. She glances at the $ in front of a number to be sure it's a price, but what she writes in the book is only the number. In a regex, "or" is written with alternation |: match the pattern on the left, or the pattern on the right. The glance is lookahead and lookbehind (together called lookaround): they peek at what comes after or before a position, without putting it in the result. Checked, not taken.
| means "or"
console.log(chat.match(/tart|cheese/gi)); // ['Tart', 'Cheese', 'tart', 'cheese', 'TART']
console.log(chat.match(/\d+ (?:dollars|bucks)/g)); // ['90 dollars', '75 bucks', '255 dollars']
console.log("cheese sticks 90 USD, snowballs 75 bucks".match(/\d+ (?:dollars|USD|bucks)/g)); // ['90 USD', '75 bucks']
tart|cheesematches either of them, anywhere.(?:dollars|bucks)keeps the choice inside the group: a number, a space, thendollarsorbucks. The non-capturing group from the previous lesson fits here, because we don't need to store the unit.- The choices are tried from the left. The first one that fits is used at once, not the longest:
"$85".match(/\$|\$\d+/)[0]is only'$'. Put the longer choice first:/\$\d+|\$/gives'$85'.
| splits the whole pattern
| has the lowest priority. Without a group, it splits the whole pattern into a left and a right.
console.log(chat.match(/\d+ dollars|bucks/g)); // ['90 dollars', 'bucks', '255 dollars']
console.log(/^\d+ dollars|bucks$/.test("ten bucks")); // true
console.log(/^\d+ (?:dollars|bucks)$/.test("ten bucks")); // false
console.log(/^\d+ (?:dollars|bucks)$/.test("90 dollars")); // true
\d+ dollars|bucksmeans\d+ dollars, or the wordbuckson its own. From75 bucksonly'bucks'is taken, without its number. So the result is not the three prices90 dollars,75 bucksand255 dollars.^\d+ dollars|bucks$means^\d+ dollarsorbucks$. The textten buckshas no digits, but it ends inbucks, so it passes the validation. Wrap the choices:^\d+ (?:dollars|bucks)$.
Lookahead: (?=...) and (?!...)
A lookahead checks what comes after the current position, without taking it.
console.log(chat.match(/\d+(?= dollars)/g)); // ['90', '255']
console.log("90 dollars".match(/\d+(?: dollars)/)[0], "90 dollars".match(/\d+(?= dollars)/)[0]); // '90 dollars' '90'
console.log("100px".match(/\d+(?=px)/)?.[0]); // '100'
console.log("foo bar".match(/foo(?! bar)/)); // null
console.log("foo baz".match(/foo(?! bar)/)[0]); // 'foo'
(?= dollars)means "must be followed bydollars", butdollarsstays out of the result. Compare(?: dollars), which takesdollarstoo.(?! bar)means "must not be followed bybar". In"foo bar",foois followed bybar, so the result isnull.- A lookaround is zero-width: it eats no character and doesn't move the position.
Lookbehind: (?<=...) and (?<!...)
The same, but it checks what comes before the current position.
console.log(chat.match(/\$\d+/g)); // ['$85', '$165', '$170']
console.log(chat.match(/(?<=\$)\d+/g)); // ['85', '165', '170']
console.log(chat.match(/(?<!PO-)\b\d{4}\b/g)); // ['7700']
(?<=\$)means "must come after$". The number is taken; the$is only glanced at.(?<!PO-)means "must not come afterPO-". Four digits standing alone are found in Bayu's phone number (7700), but0412and0413of the order codes are skipped.- Lookbehind came to JavaScript in ES2018. Chrome and Firefox have supported it for a long time, Safari only since version 16.4 (2023). In an older Safari, a pattern with a lookbehind throws a SyntaxError.
💡 Several conditions at one position
Several lookaheads in a row are checked from the same position. It's a popular way to check several conditions at once.
const strong = /^(?=.*\d)(?=.*[A-Z]).{8,}$/;
console.log(strong.test("tarts2026"), strong.test("Tarts2026")); // false true
(?=.*\d) asks for a digit, (?=.*[A-Z]) asks for an uppercase letter, then .{8,} asks for at least 8 characters. All of them are checked from ^.
⚠️ When | reaches too far and a lookahead cuts a number
^a|b$without a group. It means^aorb$, not "all of it is a or b". Validation always uses^(?:a|b)$.(?!...)makes a number back off.chat.match(/\d+(?! dollars)/g)also gives'9'from90 dollarsand'25'from255 dollars:\d+steps back one digit until what follows isn'tdollars. Forbid a digit too:/\d+(?!\d| dollars)/g. The same happens with(?<!\$): from$85it takes5.- Mixing up
(?=and(?:.(?: dollars)takesdollars,(?= dollars)only glances. - The order of the choices. The first choice that matches wins, so put the long one first.
TL;DR: | means or, and it splits the whole pattern unless a group wraps it: \d+ dollars|bucks takes the word bucks without its number, while \d+ (?:dollars|bucks) gives 90 dollars, 75 bucks, 255 dollars. Validate with ^(?:a|b)$, because ^a|b$ lets ten bucks through. A lookahead (?=...) asks for something after, (?!...) asks for nothing of that after; a lookbehind (?<=...) and (?<!...) do the same for before. They only glance and take nothing: "100px".match(/\d+(?=px)/)?.[0] gives "100", (?<=\$)\d+ gives the number without $, and "foo bar".match(/foo(?! bar)/) gives null. Watch out: (?!...) and (?<!...) can cut a number short.
⚡ | means "or"
Write:
console.log(chat.match(/\d+ (?:dollars|bucks)/g)); // ['90 dollars', '75 bucks', '255 dollars']
Meaning: | matches the pattern on its left or the one on its right. Keep the choices inside a group (?:...), because without a group, | splits the whole pattern.
⚡ Without a group, | reaches too far
Write:
console.log(/^\d+ dollars|bucks$/.test("ten bucks"));
Guess first: ten bucks has no digits, so it isn't a price this pattern wants. Is the result true or false?
true. The pattern reads as ^\d+ dollars or bucks$, and ten bucks ends in bucks. The right validation is /^\d+ (?:dollars|bucks)$/.
Meaning: Validation always uses ^(?:a|b)$, not ^a|b$.
⚡ Lookaround only glances
Write:
console.log(chat.match(/\d+(?= dollars)/g)); // ['90', '255']
console.log(chat.match(/(?<=\$)\d+/g)); // ['85', '165', '170']
Meaning: (?=...) asks for something after, (?<=...) for something before, and that part isn't taken. (?!...) and (?<!...) are the opposite: that part must not be there.