Reading history

JavaScript Regular Expressions (RegExp) Tutorial

5 min read 0 views

Learn JavaScript regular expressions: test, match, replace and split, flags, character classes, quantifiers, anchors, capture groups and validation patterns.

Checking that a phone number has 11 digits, pulling every date out of a paragraph, or squeezing repeated spaces into one: these jobs are tedious with plain string methods. A regular expression (regex) is a short pattern that describes the text you are looking for, and JavaScript can test, search and replace with it in a single line. This lesson teaches the most useful parts of the pattern language with practical examples.

In this lesson you will learn

  • Writing patterns with /.../ and flags such as g and i
  • test, match, replace and split
  • Character classes, quantifiers and anchors
  • Capture groups and named groups
  • Validation patterns for emails, phone numbers and passwords

This lesson builds on JavaScript Strings.

Searching and Replacing

// Creating and testing regular expressions
const digits = /\d+/;                    // one or more digits
console.log(digits.test("Room 204"));    // true
console.log(digits.test("Room B"));      // false

// match with the g flag returns every match
const text = "Call 01711-223344 or 01911-556677";
console.log(text.match(/\d{5}-\d{6}/g));

// i flag: ignore case
console.log(/javascript/i.test("I love JavaScript"));

// replace and replaceAll
console.log("2026-11-16".replace(/-/g, "/"));
console.log("  too    many   spaces ".trim().replace(/\s+/g, " "));

// Capture groups pull out parts of a match
const date = /(\d{4})-(\d{2})-(\d{2})/;
const [, year, month, day] = "Due: 2026-12-01".match(date);
console.log(year, month, day);

// Named groups are easier to read
const m = "Due: 2026-12-01".match(/(?<y>\d{4})-(?<mo>\d{2})-(?<d>\d{2})/);
console.log(m.groups.d + "/" + m.groups.mo + "/" + m.groups.y);

Output

true
false
[ '01711-223344', '01911-556677' ]
true
2026/11/16
too many spaces
2026 12 01
01/12/2026
  • A pattern is written between slashes. \d means any digit and + means “one or more”, so /\d+/ matches a run of digits.
  • pattern.test(text) returns true or false, the quickest check.
  • text.match(pattern) with the g (global) flag returns an array of every match. {5} means exactly five.
  • The i flag ignores upper and lower case.
  • replace(/-/g, "/") replaces every hyphen; without g only the first would change. \s+ matches any run of spaces, tabs or newlines.
  • Parentheses create capture groups. Without g, match returns the full match first, then each group, which destructuring unpacks. (?<name>...) creates a named group, read from match.groups.

Validating Input

// Practical validation patterns
const patterns = {
  email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
  bdMobile: /^01[3-9]\d{8}$/,              // Bangladeshi mobile number
  postcode: /^\d{4}$/,
  strongPassword: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/,
};

const tests = [
  ["email", "student@example.com"],
  ["email", "student@example"],
  ["bdMobile", "01712345678"],
  ["bdMobile", "0171234567"],
  ["postcode", "1207"],
  ["strongPassword", "secret"],
  ["strongPassword", "Secret2026"],
];

for (const [name, value] of tests) {
  const ok = patterns[name].test(value);
  console.log(`${name.padEnd(15)} ${value.padEnd(20)} ${ok ? "valid" : "invalid"}`);
}

// Split on several separators at once
console.log("red, green;blue  yellow".split(/[,;\s]+/));

Output

email           student@example.com  valid
email           student@example      invalid
bdMobile        01712345678          valid
bdMobile        0171234567           invalid
postcode        1207                 valid
strongPassword  secret               invalid
strongPassword  Secret2026           valid
[ 'red', 'green', 'blue', 'yellow' ]
  • ^ and $ anchor the pattern to the start and end of the text. Without them, /\d{4}/ would accept “abc12345xyz” because it contains four digits somewhere.
  • The email pattern means “some characters without spaces or @, an @, more characters, a dot, more characters”. It catches typing mistakes; real verification needs a confirmation email.
  • 01[3-9]\d{8} matches 11-digit mobile numbers starting 013 to 019. [3-9] is a range of allowed characters.
  • (?=.*[A-Z]) is a lookahead: “somewhere ahead there is a capital letter”, without consuming any characters. Chaining several lookaheads checks several rules at once.
  • split(/[,;\s]+/) splits on commas, semicolons or spaces in any combination.

Pattern Cheat Sheet

TokenMeaningExample
.Any character except newline/h.t/ matches hat, hot
\d, \w, \sDigit, word character, whitespace/\w+/
\D, \W, \SThe opposite of each/\D/ any non-digit
[abc], [^abc]One of, none of/[aeiou]/g
*, +, ?0 or more, 1 or more, 0 or 1/colou?r/
{n}, {n,m}Exactly n, between n and m/\d{2,4}/
^, $Start, end/^\d+$/ only digits
a|bEither/jpg|png/
\bWord boundary/\bcat\b/ not “category”

To match a special character literally, escape it with a backslash: \. matches a real dot. new RegExp(text, "g") builds a pattern from a string at run time.

Common Mistakes

  1. Forgetting ^ and $ in validation, so extra characters slip through.
  2. Forgetting the g flag with replace, so only the first match changes.
  3. Not escaping dots: /a.b/ also matches “axb”.
  4. Trying to validate everything with one giant regex; several small checks are easier to read and give better error messages.

Practice Exercises

Exercise 1. Write a pattern that accepts a student ID like CSE-2026-014: three capital letters, a hyphen, four digits, a hyphen, three digits.

Show answer
const id = /^[A-Z]{3}-\d{4}-\d{3}$/;
console.log(id.test("CSE-2026-014"));  // true
console.log(id.test("cse-2026-14"));   // false

Exercise 2. Count the vowels in “Regular expressions are powerful”.

Show answer
const text = "Regular expressions are powerful";
console.log((text.match(/[aeiou]/gi) || []).length);   // 12

|| [] avoids an error when there are no matches, because match then returns null.

Frequently Asked Questions

Are regular expressions the same in every language?

The core syntax is shared by JavaScript, Python, Java, PHP and most tools, so what you learn here transfers. Advanced features and flags differ slightly between languages.

How can I test a regex quickly?

Use the browser console, or an online tester such as regex101 with the JavaScript flavour selected; it explains each part of the pattern and highlights matches.

Summary

  • A regex is a pattern between slashes, with optional flags (g, i, m).
  • test checks, match finds, replace substitutes, split divides.
  • Anchor validation patterns with ^ and $.
  • Groups capture parts of a match; named groups make code clearer.

Next: The this Keyword in JavaScript.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *