Regular expressions

Topic 3 of 3 in Built-in objects7 min readBeginnerFree course

Overview

A regular expression (regex) is a pattern for matching text. You write it between slashes.

JavaScript
const hasNumber = /\d/;
hasNumber.test('Lesson 4'); // true
hasNumber.test('Lesson');   // false

Where string methods like includes look for exact text, a regex describes a shape: “some digits”, “a word followed by @”, “exactly six numbers”. They’re ideal for validating input, extracting pieces from text and doing clever find-and-replace.

The regex /(\d{4})-(\d{2})-(\d{2})/g broken down: \d means a digit, {4} means exactly four, the dash is a literal dash, brackets make capture groups and g is a flag. Matching ‘2026-12-03’ gives group 1 year 2026, group 2 month 12 and group 3 day 03.

Common building blocks

Pattern Matches
abc the exact text “abc”
\d a digit (0–9)
\w a letter, digit or underscore
\s a space, tab or newline
\D \W \S the opposite of the above
. any character except a newline
[aeiou] any one of these characters
[a-z] [0-9] any one character in a range
[^0-9] any character not in the set
a|b a or b
\. \? \( a literal ., ?, ( — backslash escapes special characters

Quantifiers: how many?

Pattern Meaning
+ one or more
* zero or more
? optional (zero or one)
{3} exactly 3
{2,4} between 2 and 4
{2,} 2 or more

A quantifier applies to the thing just before it: \d+ means “one or more digits”, colou?r matches “color” and “colour”.

Anchors: where?

^ matches the start of the text and $ the end. Without them, a pattern can match anywhere inside:

JavaScript
/\d{6}/.test('PIN 4110012');    // true — six digits appear somewhere
/^\d{6}$/.test('4110012');      // false — the whole text must be six digits
/^\d{6}$/.test('411001');       // true

For validation, you almost always want both anchors. \b matches a word boundary: /\bcat\b/ finds “cat” but not “concatenate”.

Flags

JavaScript
/java/i.test('JavaScript');         // true — i ignores case
'a-b-c'.replace(/-/g, ' ');          // 'a b c' — g replaces all
Flag Effect
g global — find all matches, not just the first
i ignore case
m multiline — ^ and $ match at each line
s dotAll — . also matches newlines
u Unicode-aware (handles emoji properly)

Using a regex

JavaScript
const text = 'Call 98765 43210 or 91234 56789';

/\d{5}/.test(text);           // true — is there a match?
text.search(/\d/);            // 5 — index of the first match
text.match(/\d{5}/);          // ['98765', index: 5, …] — first match with details
text.match(/\d{5}/g);         // ['98765', '43210', '91234', '56789'] — all matches
text.replace(/\d/g, '#');     // 'Call ##### ##### or ##### #####'
text.split(/\s+or\s+/);       // ['Call 98765 43210', '91234 56789']

match with the g flag returns just the matched strings, or null if there are none — hence the ?? [] in this topic’s exercise.

Extracting with groups

Brackets capture parts of a match:

JavaScript
const date = '2026-12-03';
const [, year, month, day] = date.match(/(\d{4})-(\d{2})-(\d{2})/);

Index 0 of the result is the whole match; groups follow in order. Named groups read even better:

JavaScript
const { groups } = date.match(/(?<year>\d{4})-(?<month>\d{2})/);
groups.year; // '2026'

All matches with their groups

matchAll (which requires the g flag) gives every match along with its groups:

JavaScript
const text = 'Asha: 90, Ravi: 75';
for (const m of text.matchAll(/(\w+): (\d+)/g)) {
  console.log(m[1], Number(m[2])); // 'Asha' 90, then 'Ravi' 75
}

Using groups in replacements

In a replacement string, $1, $2 refer to groups. You can also pass a function:

JavaScript
'2026-12-03'.replace(/(\d+)-(\d+)-(\d+)/, '$3/$2/$1'); // '03/12/2026'

'hello world'.replace(/\b\w/g, (letter) => letter.toUpperCase()); // 'Hello World'

Greedy versus lazy

Quantifiers are greedy: they grab as much as they can. Add ? to make them lazy:

JavaScript
const html = '<b>one</b> and <b>two</b>';
html.match(/<b>.*<\/b>/)[0];  // '<b>one</b> and <b>two</b>' — greedy
html.match(/<b>.*?<\/b>/)[0]; // '<b>one</b>' — lazy

Building a regex from a string

When part of the pattern comes from a variable, use the RegExp constructor. Remember that backslashes need doubling inside a normal string:

JavaScript
const word = 'cat';
const re = new RegExp(`\\b${word}\\b`, 'gi');
'Cat and cat'.match(re); // ['Cat', 'cat']

If the variable comes from a user, escape special characters first, or a search for “1+1” would be read as a pattern.

Keep them small. A regex that needs a paragraph to explain is usually clearer as a few lines of ordinary code. Test patterns in an online tester such as regex101.com, which explains each part as you type.

Exercise

Extract hashtags

Write hashtags(text) that returns all hashtags (like #js) found in the text. Then write isPinCode(text) that returns true only for exactly six digits.

JavaScript
function hashtags(text) {
  // your code here
}

function isPinCode(text) {
  // your code here
}

hashtags('Learning #js and #css today'); // ['#js', '#css']
isPinCode('411001'); // true
isPinCode('41100');  // false

Summary

  • A regular expression describes a text pattern, written between slashes.
  • test checks for a match; match, matchAll and replace work with the results.
  • Quantifiers (+, *, ?, {n}) say how many; ^ and $ anchor to the start and end.
  • Brackets ( ) capture parts of the match; (?<name> ) names them.
  • Flags change behaviour: g for all matches, i to ignore case.