Regular Expressions
A regular expression (often shortened to regex) is a pattern that describes a set of strings, used to search, validate, extract and replace text. Where includes("@") can only look for fixed text, the regex /^\d{5}$/ describes "exactly five digits and nothing else", which is a US ZIP code. Regular expressions are a small language of their own, with a compact and admittedly cryptic syntax; this lesson covers the building blocks, the next covers groups and assertions, and the third covers the methods that use them.
In One Minute
- Write a regex as a literal
/pattern/flags, or build one from a string withnew RegExp("pattern", "flags"). - Character classes match one character from a set:
\d(digit),\w(word character),\s(whitespace),[aeiou],[^0-9]. - Quantifiers repeat:
*(0 or more),+(1 or more),?(0 or 1),{3},{2,5}. - Anchors pin a match:
^(start),$(end),\b(word boundary). - Flags change behavior:
g(all matches),i(ignore case),m,s,u,v,y,d.
Creating a Regular Expression
Syntax
const re1 = /pattern/flags; // literal: fixed patterns
const re2 = new RegExp("pattern", "flags"); // constructor: patterns built at run timeExample
const zip = /^\d{5}$/;
console.log(zip.test("75201"));
console.log(zip.test("7520"));
console.log(zip.test("75201-1234"));
const word = "fee";
const dynamic = new RegExp(`\\b${word}\\b`, "i");
console.log(dynamic.source, dynamic.flags);
console.log(dynamic.test("Late FEE applied"));true
false
false
\bfee\b i
trueExplanation: test returns true if the pattern matches somewhere in the string. With the constructor, the pattern is a normal string, so every backslash must be doubled ("\\b" produces the two characters \b). Use literals when you know the pattern in advance, and the constructor when part of it comes from a variable.
Literal Characters and Special Characters
Most characters match themselves: /fee/ matches the text "fee". These metacharacters have special meanings and must be escaped with \ to match literally:
. ^ $ * + ? ( ) [ ] { } | \ /console.log(/\$120\.00/.test("Total: $120.00"));
console.log(/1.5/.test("125"));
console.log(/1\.5/.test("125"));true
true
falseThe unescaped . means "any character", so /1.5/ matches the "125" in "125". Escape it to match a real dot.
Character Classes
A character class matches one character from a set:
| Pattern | Matches one... |
|---|---|
. | Any character except a line break (any at all with the s flag) |
\d | Digit, 0 to 9 |
\D | Non-digit |
\w | Word character: letter, digit or _ (ASCII only) |
\W | Non-word character |
\s | Whitespace: space, tab, line break and others |
\S | Non-whitespace |
[abc] | a, b or c |
[a-z], [0-9A-F] | A character in a range |
[^abc] | Any character except a, b or c |
\p{L} (with u or v) | Any Unicode letter, in any script |
const text = "Navika paid $120 on 01/05, Srihitha paid $85.";
console.log(text.match(/\d/g));
console.log(text.match(/[A-Z]/g));
console.log(text.match(/[^\w\s]/g));
console.log("Zoë Chloé".match(/\p{L}+/gu));
console.log("Zoë Chloé".match(/\w+/g));['1', '2', '0', '0', '1', '0', '5', '8', '5']
['N', 'S']
['$', '/', ',', '$', '.']
['Zoë', 'Chloé']
['Zo', 'Chlo']Explanation: \w only knows ASCII letters, so it splits "Zoë" at the ë. For names and other human text, use the Unicode property \p{L} with the u (or v) flag.
Quantifiers
A quantifier after an item says how many times it may repeat:
| Quantifier | Meaning |
|---|---|
* | 0 or more |
+ | 1 or more |
? | 0 or 1 (optional) |
{n} | Exactly n |
{n,} | n or more |
{n,m} | Between n and m |
console.log("Paid $120, $85 and $1250".match(/\$\d+/g));
console.log(/^\d{3}-\d{4}$/.test("555-0100"));
console.log(/^colou?r$/.test("color"), /^colou?r$/.test("colour"));
console.log("aaa ab a".match(/a{2,}/g));['$120', '$85', '$1250']
true
true true
['aaa']Greedy vs Lazy
Quantifiers are greedy by default: they match as much as possible. Add ? after a quantifier to make it lazy (as little as possible):
const html = "<b>Navika</b> and <b>Advitha</b>";
console.log(html.match(/<b>.*<\/b>/)[0]);
console.log(html.match(/<b>.*?<\/b>/)[0]);
console.log(html.match(/<b>.*?<\/b>/g));<b>Navika</b> and <b>Advitha</b>
<b>Navika</b>
['<b>Navika</b>', '<b>Advitha</b>']The greedy .* runs to the last </b> in the string. The lazy .*? stops at the first one. A more precise pattern, <b>[^<]*<\/b> ("any characters except <"), avoids the question entirely. (For real HTML, use the DOM, not regular expressions.)
Anchors
Anchors match a position, not a character:
| Anchor | Matches at |
|---|---|
^ | The start of the string (or of each line with the m flag) |
$ | The end of the string (or of each line with m) |
\b | A word boundary: between a word character and a non-word character |
\B | Not a word boundary |
console.log(/\d{5}/.test("ZIP: 75201 (Dallas)"));
console.log(/^\d{5}$/.test("ZIP: 75201 (Dallas)"));
console.log("late fee, latest note".match(/\blate\b/g));
console.log("late fee, latest note".match(/late/g));true
false
['late']
['late', 'late']Validation patterns need ^ and $. Without them, /\d{5}/ accepts any string that merely contains five digits. \b matches whole words only, so "latest" isn't counted.
Flags
| Flag | Name | Effect |
|---|---|---|
g | global | Find all matches, not just the first |
i | ignoreCase | Case-insensitive |
m | multiline | ^ and $ match at each line's start and end |
s | dotAll | . also matches line breaks |
u | unicode | Full Unicode: code points, \p{...} |
v | unicodeSets | Like u, plus set operations in classes (ES2024) |
y | sticky | Match only at lastIndex |
d | hasIndices | Record start and end indices of each group |
const notes = "Paid: Navika\npaid: Srihitha\nDue: Advitha";
console.log(notes.match(/^paid: (\w+)$/gim));
console.log(/a.b/.test("a\nb"), /a.b/s.test("a\nb"));
console.log("😀".match(/./g).length, "😀".match(/./gu).length);['Paid: Navika', 'paid: Srihitha']
false true
2 1Explanation: g returns every match, i ignores case, and m lets ^ and $ work on each line. s lets . cross line breaks. Without u, . matches each UTF-16 code unit, so an emoji counts as two characters.
In Practice
The Fee Tracker validates form fields with anchored patterns. Each pattern is named, so the code says what it checks:
const PATTERNS = {
zip: /^\d{5}(-\d{4})?$/,
phone: /^\(?\d{3}\)?[\s.-]?\d{3}[-.]?\d{4}$/,
amount: /^\$?\d{1,6}(\.\d{2})?$/,
studentId: /^S-\d{4}$/i,
};
const form = { zip: "94103-1234", phone: "(415) 555-0199", amount: "$120.5", studentId: "s-0042" };
for (const [field, value] of Object.entries(form)) {
console.log(field.padEnd(10), value.padEnd(15), PATTERNS[field].test(value) ? "ok" : "invalid");
}zip 94103-1234 ok
phone (415) 555-0199 ok
amount $120.5 invalid
studentId s-0042 ok$120.5 fails because the pattern requires exactly two digits after a decimal point. (-\d{4})? makes the ZIP+4 part optional; groups like this are the subject of the next lesson.
Common Mistakes
Forgetting ^ and $ in validation. The pattern matches anywhere inside the string.
Not escaping ., $ or (. They are metacharacters. Write \., \$, \(.
Single backslashes in new RegExp strings. new RegExp("\d") is just d. Write "\\d".
Expecting \w to match accented letters. It is ASCII only. Use \p{L} with the u flag.
Practice
Challenge: Write a pattern for a payment reference like PAY-2026-000123: the letters PAY, a dash, a four-digit year starting with 20, a dash, and exactly six digits. Test it on a valid reference and two invalid ones.
Show solution
const REFERENCE = /^PAY-20\d{2}-\d{6}$/;
console.log(REFERENCE.test("PAY-2026-000123"));
console.log(REFERENCE.test("PAY-1999-000123"));
console.log(REFERENCE.test("PAY-2026-12345"));true
false
falseKey Takeaways
| Pattern | Meaning |
|---|---|
\d, \w, \s | Digit, word character, whitespace |
[a-z], [^0-9] | Range, negated set |
+, *, ?, {n,m} | Repetition |
^...$ | Whole string |
\b | Word boundary |
/.../giu | All matches, any case, Unicode |
Was this tutorial helpful?