Complete JavaScript Course Module 14: Advanced: Advanced Language Features

Regular Expressions in JavaScript

  • Beginner
  • Lesson 14.6
  • 6 min read
  • 66 of 76 in the course

In short

Regular expressions in JavaScript (regex) are patterns for finding, checking and replacing text. Learn how to create them, use test, match and replace, and write practical patterns. What is a regular expression? A regular expression (or regex) is a small pattern that describes text.

Regular expressions in JavaScript (regex) are patterns for finding, checking and replacing text. Learn how to create them, use test, match and replace, and write practical patterns.

What is a regular expression?

A regular expression (or regex) is a small pattern that describes text. Instead of searching for one exact word, you can search for "any 5 digits" or "a word that starts with a capital letter".

Think of it as a search with wildcards. In a phone book, you might look for "every name starting with M and ending with -son". A regex lets you write that kind of rule for a computer.

Regex can look scary at first because it uses many symbols. The trick is to learn a few pieces at a time and read patterns left to right.

How to create a regex in JavaScript

There are two ways to create one.

// 1. Regex literal: the pattern between slashes
const pattern1 = /cat/;

// 2. RegExp constructor: useful when the pattern comes from a variable
const word = 'cat';
const pattern2 = new RegExp(word, 'i');   // 'i' is a flag (ignore case)

console.log(pattern1.test('I love my cat'));   // Output: true
console.log(pattern2.test('CATS are great'));  // Output: true

Use the literal /.../ most of the time. Use new RegExp() when you build the pattern from user input or a variable.

Testing, matching and replacing text

These are the four methods you will use most.

  • regex.test(text) returns true or false.
  • text.match(regex) returns the match details (or null), or all matches when the g flag is used.
  • text.matchAll(regex) returns every match with details; it needs the g flag.
  • text.replace(regex, newText) replaces matches with something new.
const message = 'Order 123 shipped. Order 456 is late.';

console.log(/late/.test(message));        // Output: true

console.log(message.match(/\d+/));        // first match: ["123", index: 6, ...]
console.log(message.match(/\d+/g));       // Output: ["123", "456"]

for (const m of message.matchAll(/Order (\d+)/g)) {
  console.log(`Found order ${m[1]} at position ${m.index}`);
}
// Output:
// Found order 123 at position 0
// Found order 456 at position 19

console.log(message.replace(/Order/g, 'Package'));
// Output: Package 123 shipped. Package 456 is late.

\d+ means "one or more digits". Without the g flag, match() and replace() only handle the first match.

Regex building blocks: character classes, quantifiers and anchors

Character classes

A character class matches one character from a group.

PatternMatches
.Any character except a line break
\dA digit 0–9
\wA letter, digit or underscore
\sA space, tab or line break
\D, \W, \SThe opposite of the lowercase versions
[aeiou]Any one of these letters
[a-z]Any lowercase letter from a to z
[^0-9]Anything that is NOT a digit

Quantifiers

A quantifier says how many times the thing before it can repeat.

PatternMeans
*0 or more times
+1 or more times
?0 or 1 time (optional)
{3}Exactly 3 times
{2,4}Between 2 and 4 times

Anchors

Anchors match a position, not a character. ^ means "start of the text" and $ means "end of the text". \b means a word boundary (the edge of a word).

console.log(/^\d{5}$/.test('90210'));     // Output: true  (exactly 5 digits)
console.log(/^\d{5}$/.test('902101'));    // Output: false (6 digits)
console.log(/\d{5}/.test('abc902101'));   // Output: true  (no anchors: 5 digits anywhere)

console.log(/\bcat\b/.test('concatenate'));  // Output: false
console.log(/\bcat\b/.test('my cat sleeps')); // Output: true

Common mistake: Forgetting ^ and $ when validating. Without them, /\d{5}/ also accepts abc123456xyz, because it only needs 5 digits somewhere inside.

Groups, named groups and flags

Parentheses ( ) make a group. A group lets you apply a quantifier to several characters and also "captures" that part so you can use it later. A named group (?<name>...) gives the captured part a readable name.

const date = '2026-10-01';
const datePattern = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/;

const result = date.match(datePattern);
console.log(result.groups.year);   // Output: 2026
console.log(result.groups.day);    // Output: 01

// Use the groups in replace with $<name>
console.log(date.replace(datePattern, '$<day>/$<month>/$<year>'));
// Output: 01/10/2026

Flags go after the closing slash and change how the whole pattern works.

  • g (global): find all matches, not just the first.
  • i (ignore case): A and a count as the same.
  • m (multiline): ^ and $ match at the start and end of each line, not just the whole text.
const list = 'apple\nBanana\navocado';
console.log(list.match(/^a\w+/gm));    // Output: ["apple", "avocado"]
console.log(list.match(/^b\w+/gim));   // Output: ["Banana"]

Practical regex examples: email, phone number and slug

Here are three patterns you may really use, with honest limits.

// 1. Email-ish check: something@something.something, no spaces
const looksLikeEmail = (text) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(text);
console.log(looksLikeEmail('ana@example.com'));  // Output: true
console.log(looksLikeEmail('ana@example'));      // Output: false

// 2. Phone number: remove spaces, dashes, dots and brackets, then check 7-15 digits
const isPhone = (text) => /^\+?\d{7,15}$/.test(text.replace(/[\s\-.()]/g, ''));
console.log(isPhone('+44 20 7946 0958'));  // Output: true
console.log(isPhone('call me'));           // Output: false

// 3. Turn a blog title into a URL slug
const slugify = (title) =>
  title
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9\s-]/g, '')   // remove symbols
    .replace(/[\s-]+/g, '-')        // spaces or dashes become one dash
    .replace(/^-+|-+$/g, '');       // remove dashes at the start or end

console.log(slugify('  10 Tips for Learning JavaScript!  '));
// Output: 10-tips-for-learning-javascript

The email check only catches obvious typos. The only real way to know an email works is to send a message to it. The phone check accepts many international formats but does not know if a number really exists. The slug function removes accented letters like é; for other languages you may need a smarter approach.

Tip: Keep regex short and add a comment explaining it. If a pattern grows huge, split the work into a few simple steps instead. Test your patterns with many real inputs.

Practice exercise

Write a function findHashtags(text) that returns all hashtags in a social media post, for example 'Loving #JavaScript and #webdev today!' should give ['#JavaScript', '#webdev']. Then write isHexColor(text) that returns true for values like #ff8800 or #FFF.

Hint: use match() with the g flag for the first one. For the second, try ^# followed by 3 or 6 characters from [0-9a-f] and the i flag.

Frequently asked questions

Should I use regex to validate email addresses?

Use a simple regex only to catch obvious typos, together with type="email" on the input. Full email rules are very complex, so the real test is sending a confirmation email.

What is the difference between match() and matchAll()?

With the g flag, match() returns just the matched strings. matchAll() returns every match with its details, such as groups and position, and it requires the g flag.

Why does my regex with the g flag give different test() results?

A regex with g remembers where it stopped (its lastIndex), so calling test() again continues from there. For simple yes/no checks, do not use the g flag.

Key takeaways

  • A regex is a pattern for finding, checking or replacing text, written as /pattern/flags.
  • Use test() for yes/no, match() and matchAll() to find, and replace() to change text.
  • Character classes, quantifiers and anchors are the main building blocks; use ^ and $ when validating.
  • Groups and named groups capture parts of a match, and flags g, i and m change the search.
  • Regex validation catches typos, but it cannot prove an email or phone number is real.