Regular Expressions

Updated · 7 min read
mediumES2026javascriptregexregular-expressionspatterns

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 with new 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

syntax.js
const re1 = /pattern/flags;                    // literal: fixed patterns
const re2 = new RegExp("pattern", "flags");    // constructor: patterns built at run time

Example

create.js▶ Try it
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"));
Output
true
false
false
\bfee\b i
true

Explanation: 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:

Metacharacters
.  ^  $  *  +  ?  (  )  [  ]  {  }  |  \  /
escape.js▶ Try it
console.log(/\$120\.00/.test("Total: $120.00"));
console.log(/1.5/.test("125"));
console.log(/1\.5/.test("125"));
Output
true
true
false

The 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:

PatternMatches one...
.Any character except a line break (any at all with the s flag)
\dDigit, 0 to 9
\DNon-digit
\wWord character: letter, digit or _ (ASCII only)
\WNon-word character
\sWhitespace: space, tab, line break and others
\SNon-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
classes.js▶ Try it
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));
Output
['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:

QuantifierMeaning
*0 or more
+1 or more
?0 or 1 (optional)
{n}Exactly n
{n,}n or more
{n,m}Between n and m
quantifiers.js▶ Try it
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));
Output
['$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):

greedy.js▶ Try it
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));
Output
<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:

AnchorMatches 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)
\bA word boundary: between a word character and a non-word character
\BNot a word boundary
anchors.js▶ Try it
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));
Output
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

FlagNameEffect
gglobalFind all matches, not just the first
iignoreCaseCase-insensitive
mmultiline^ and $ match at each line's start and end
sdotAll. also matches line breaks
uunicodeFull Unicode: code points, \p{...}
vunicodeSetsLike u, plus set operations in classes (ES2024)
ystickyMatch only at lastIndex
dhasIndicesRecord start and end indices of each group
flags.js▶ Try it
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);
Output
['Paid: Navika', 'paid: Srihitha']
false true
2 1

Explanation: 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:

validate.js▶ Try it
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");
}
Output
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
reference.js▶ Try it
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"));
Output
true
false
false

Quick check: Regular expressions

3 questions
1What does \d+ match?
2Why does /\d{5}/ accept "abc12345xyz"?
3Which flag makes a regex find every match instead of only the first?

Key Takeaways

PatternMeaning
\d, \w, \sDigit, word character, whitespace
[a-z], [^0-9]Range, negated set
+, *, ?, {n,m}Repetition
^...$Whole string
\bWord boundary
/.../giuAll matches, any case, Unicode

Was this tutorial helpful?

Lesson 64 of 139