AdvancedLesson 27 of 305 min read

Regular expressions: patterns for searching text

Search, validate and transform text with regular expressions: character classes, quantifiers, groups, flags and replace.

In this lesson you will

  • Read and write basic regex patterns
  • Validate input with anchors and quantifiers
  • Extract parts with groups
  • Replace and split text with regex

About 20 minutes

A pattern language for text

You are checking a phone number box. The visitor might type 0300-1234567, or 03001234567, or with spaces. Writing ten if statements to handle each variety is painful. A regular expression (regex or regexp) is a compact pattern that describes a whole family of strings at once: “a zero, a three, two digits, an optional dash, then seven digits”. Regexes look like cat-walks-on-keyboard at first, but they are built from a small set of pieces, and learning those pieces is quick.

Creating and testing a regex

const pattern = /cat/;                  // between slashes
console.log(pattern.test("concatenate"));   // true: contains cat
console.log(pattern.test("dog"));           // false

const sameThing = new RegExp("cat");        // from a string

console.log(/cat/i.test("CAT"));            // i = ignore case

The building blocks

Pattern Matches
abc The exact text abc
. Any one character (except a new line)
\d A digit 0-9
\w A letter, digit or underscore
\s A space, tab or new line
[abc] One of a, b or c
[a-z] One lowercase letter
[^0-9] Anything except a digit
^ and $ Start and end of the text
a|b a or b

How many times? Quantifiers

Pattern Meaning
a* zero or more a
a+ one or more a
a? zero or one a (optional)
a{3} exactly three a
a{2,4} two to four a
(abc)+ the group abc, one or more times
const phone = /^03\d{2}-?\d{7}$/;

console.log(phone.test("0300-1234567"));   // true
console.log(phone.test("03001234567"));    // true
console.log(phone.test("0400-1234567"));   // false
console.log(phone.test("0300-12345"));     // false

The anchors ^ and $ are important. Without them, /\d{7}/ would happily match seven digits in the middle of a longer string. Anchored, the whole text must fit the pattern.

Write a regex that accepts a 5-digit postcode (exactly five digits, nothing else) and test it against the four values.

const postcode = /x/;   // replace this with your pattern
console.log(postcode.test('54000'));
console.log(postcode.test('5400'));
console.log(postcode.test('540001'));
console.log(postcode.test('54a00'));

/^\d{5}$/

const postcode = /^\d{5}$/;
console.log(postcode.test('54000'));   // true
console.log(postcode.test('5400'));    // false
console.log(postcode.test('540001'));  // false
console.log(postcode.test('54a00'));   // false

Finding and extracting: match and groups

const text = "Call 0300-1234567 or 0321-7654321 today";

console.log(text.match(/\d{4}-\d{7}/));            // first match
console.log(text.match(/\d{4}-\d{7}/g));           // g = all matches -> array

const date = "2026-10-31".match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(date[1], date[2], date[3]);           // 2026 10 31

// named groups are easier to read
const m = "2026-10-31".match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
console.log(m.groups.year, m.groups.day);

Replacing and splitting

console.log("a  b   c".replace(/\s+/g, " "));          // a b c
console.log("Hello World".replace(/o/g, "0"));         // Hell0 W0rld

// use captured groups in the replacement
console.log("2026-10-31".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1"));   // 31/10/2026

// a function can compute the replacement
console.log("price 20 and 35".replace(/\d+/g, n => n * 2));   // price 40 and 70

console.log("one, two;three".split(/[,;]\s*/));       // ["one","two","three"]

Turn the sentence into a URL slug: lowercase, replace anything that is not a letter or digit with a dash, and remove dashes at the start or end.

const title = '  Learn JavaScript: Regex & More!  ';
// make slug 'learn-javascript-regex-more'

title.toLowerCase().replace(/[^a-z0-9]+/g, ‘-‘).replace(/^-|-$/g, ”)

const title = '  Learn JavaScript: Regex & More!  ';
const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
console.log(slug);

Flags

Flag Effect
g Global: find all matches
i Ignore case
m ^ and $ match at each line
s Dot matches new lines
u Full Unicode support (emoji, Urdu, Arabic)

Practical patterns

const email = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;          // simple email shape
const hex   = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;         // colour like #5A28C8
const strongPassword = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;   // lookaheads
const wordsOnly = /\b\w+\b/g;                          // \b = word boundary

console.log(email.test("sara@mail.com"));
console.log(hex.test("#5A28C8"));
console.log(strongPassword.test("Passw0rdOK"));
console.log("The cat sat".match(wordsOnly).length);
Good to know

Do not try to validate email addresses perfectly with a regex. The official rules are enormous. Use a simple shape check like the one above, and confirm real addresses by sending a message.

Greedy versus lazy

const html = "<b>bold</b> and <i>italic</i>";

console.log(html.match(/<.+>/)[0]);     // greedy: "<b>bold</b> and <i>italic</i>"
console.log(html.match(/<.+?>/)[0]);    // lazy (?): "<b>" 

Tips for readable regex

  • Build them piece by piece, testing each step.
  • Use a tester tool such as regex101.com, which explains every part.
  • Comment complex ones, or split them into named parts with new RegExp.
  • If a regex is longer than a line and nobody understands it, consider ordinary code instead.
  • Beware of catastrophic backtracking: nested quantifiers like (a+)+ can freeze on long input. Keep patterns simple for user-supplied text.
Common mistake

Forgetting the anchors ^ and $ in validation. /\d{5}/.test("abc12345xyz") is true. Also remember that a regex made with g keeps a lastIndex, so repeated .test() calls on the same global regex can give alternating results. Avoid g when just testing.

Escape special characters

To match a literal dot, plus or bracket, put a backslash in front: \., \+, \(. A bare . means any character, which is a classic reason a pattern matches too much.

Try it: the regex in a form

Regular expressions earn their keep in forms. Here the idea in miniature: one pattern, tested on every keystroke, with a clear message beside the box. Notice how little code the check itself needs.

const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
input.addEventListener("input", () => {
  msg.textContent = hex.test(input.value) ? "Valid colour" : "Use a colour like #5A28C8";
});

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does \d match?

  1. A letter
  2. A space
  3. A digit
  4. A dot

\d is any digit 0-9.

What do ^ and $ do?

  1. Anchor to the start and end of the text
  2. Match dollar and caret symbols
  3. Repeat
  4. Negate

They make the whole text match.

Which flag finds all matches?

  1. i
  2. m
  3. g
  4. x

g is global.

What does a+ match?

  1. One or more a
  2. Zero or more a
  3. Exactly one a
  4. a or plus

+ means one or more.

What does .test() return?

  1. The match
  2. true or false
  3. An array
  4. A number

test answers yes or no.

Summary

  • A regex is a pattern describing many strings.
  • Anchor with ^ and $ for validation.
  • Groups capture parts; replace can reuse them.
  • Keep patterns simple and test them step by step.

Next lesson

Next: dates, times, numbers and currencies with Date and Intl.

Questions

Are regexes hard?

They look cryptic, but they are built from a small set of pieces. Build them gradually and test often.

Why does my regex match too much?

Probably a greedy quantifier or an unescaped dot. Anchor it and add ? for lazy matching.

Should I use regex to parse HTML?

No. Use the DOM or a parser. HTML is too irregular for regular expressions.

Progress is saved in this browser.