Tutorials JavaScript Regular Expressions
Ch 67 / 78
Chapter 67 Intermediate 10 min read JavaScript

Regular Expressions in JavaScript

Regular Expressions (RegEx) are powerful patterns used to search, match, and manipulate text. From form validation to parsing, they are an indispensable tool in every JavaScript developer's toolkit.

What you'll learn
What a Regular Expression is and how it works
Two ways to create a RegEx in JavaScript
Flags: g, i, m, s, u, d
Character classes, quantifiers & anchors
Capturing groups & alternation
Built-in methods: test, match, replace, split

What is a Regular Expression?

A Regular Expression (regex or regexp) is a sequence of characters that forms a search pattern. You use it to test whether a string contains a certain pattern, extract matching parts, or replace text based on a rule.

Think of it as a supercharged indexOf(). Where indexOf() only finds exact substrings, regex can match patterns — like "any 5-digit number", "an email address", or "a word that starts with a capital letter".

Search
Find whether a pattern exists anywhere in a string — useful for validation.
Extract
Pull out the specific parts that match — useful for parsing dates, emails, or URLs.
Replace
Swap out matched text with something else — useful for formatting and sanitising input.
Split
Break a string on a pattern rather than a fixed character — e.g., split on any whitespace.

Creating a Regular Expression

JavaScript gives you two ways to create a regex:

JS — Two Syntax Forms
// 1️⃣  Literal notation — use when pattern is known at write-time (preferred)
const re1 = /hello/i;      // pattern between / /  followed by optional flags

// 2️⃣  Constructor notation — use when pattern is built dynamically at runtime
const word = "hello";
const re2 = new RegExp(word, "i");  // RegExp(pattern, flags)

console.log(re1.test("Hello World"));  // true  (case-insensitive)
console.log(re2.test("Hello World"));  // true
Pro Tip
Always prefer the literal syntax /pattern/flags — it is cleaner, avoids escaping backslashes twice, and has no overhead. Use new RegExp() only when the pattern needs to be composed from a variable at runtime.

Regex Flags

Flags modify how the pattern is applied. They are placed after the closing / of a literal regex, or as the second argument of RegExp(). Multiple flags can be combined.

g
Global
Find all matches, not just the first one.
i
Case-insensitive
Ignore case differences — A matches a.
m
Multiline
^ and $ match the start/end of each line, not just the whole string.
s
Dot-all
Makes . match newline characters too.
u
Unicode
Treats pattern and string as Unicode code points. Required for emoji and non-ASCII patterns.
d
Indices
Generates indices on match results showing start/end positions (ES2022).
JS — Flag Examples
const str = "Cat cat CAT";

// g — global: all matches
console.log(str.match(/cat/g));    // ["cat"]  (only lowercase)

// gi — global + case-insensitive: every occurrence
console.log(str.match(/cat/gi));   // ["Cat", "cat", "CAT"]

// m — multiline: ^ / $ per line
const text = "first\nsecond\nthird";
console.log(text.match(/^\w+/gm));  // ["first","second","third"]

Character Classes & Quantifiers

These are the fundamental building blocks of every regex pattern:

Syntax Meaning Example
. Any character except newline /c.t/ → "cat", "cut", "c3t"
\d Any digit (0–9) /\d+/ → "42", "007"
\D Any non-digit /\D/ → "a", " ", "!"
\w Word character [a-zA-Z0-9_] /\w+/ → "hello_World"
\W Non-word character /\W/ → "@", " ", "-"
\s Whitespace (space, tab, newline) /\s+/ → trims gaps
[abc] Character set — matches a, b, or c /[aeiou]/ → vowels
[^abc] Negated set — anything NOT in set /[^0-9]/ → non-digits
^ Start of string (or line with m) /^Hello/
$ End of string (or line) /world$/
* 0 or more of the preceding /ab*/ → "a", "ab", "abbb"
+ 1 or more of the preceding /ab+/ → "ab", "abbb"
? 0 or 1 (optional) /colou?r/ → "color" or "colour"
{n} Exactly n times /\d{4}/ → "2025"
{n,m} Between n and m times /\d{2,4}/ → "12", "1234"
JS — Character Class Examples
// Match a UK postcode format (simplified): AB12 3CD
const postcode = /^[A-Z]{1,2}\d{1,2}\s\d[A-Z]{2}$/i;
console.log(postcode.test("SW1A 1AA"));  // true
console.log(postcode.test("hello"));    // false

// Extract all numbers from a sentence
const sentence = "I have 3 cats and 12 fish.";
console.log(sentence.match(/\d+/g));   // ["3", "12"]

// Optional character — matches both "colour" and "color"
console.log(/colou?r/.test("color"));   // true
console.log(/colou?r/.test("colour"));  // true

Groups & Alternation

Groups let you treat multiple characters as a unit, capture them for later use, or create "or" conditions with alternation.

(abc)
Capturing group — matches "abc" and captures it. Access via match()[1].
(?:abc)
Non-capturing group — groups without storing the match. Useful for grouping with | or quantifiers.
(?<name>abc)
Named capturing group — access via match().groups.name.
a|b
Alternation — matches "a" OR "b". Like a logical OR for patterns.
JS — Groups & Named Captures
// Capturing group — extract year, month, day from a date string
const dateStr = "2025-07-21";
const dateRe  = /(\d{4})-(\d{2})-(\d{2})/;
const m       = dateStr.match(dateRe);
console.log(m[1], m[2], m[3]);   // "2025" "07" "21"

// Named capturing group — cleaner access
const namedRe = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const { year, month, day } = dateStr.match(namedRe).groups;
console.log(year, month, day);  // "2025" "07" "21"

// Alternation — match "cat" or "dog"
const petRe = /cat|dog/gi;
console.log("I have a Cat and a Dog".match(petRe));  // ["Cat", "Dog"]

// Non-capturing group with quantifier
const repeatRe = /(?:ha){3}/;
console.log(repeatRe.test("hahaha"));   // true
console.log(repeatRe.test("haha"));     // false

JavaScript Regex Methods

Regex can be used through RegExp prototype methods and String methods. Here are the six you'll use most often:

regex.test(str)
Returns true or false. The fastest way to check if a pattern exists in a string.
str.match(regex)
Returns an array of matches, or null. Without g flag, also includes capture groups.
str.matchAll(regex)
Returns an iterator of all matches with capture groups. Requires the g flag.
str.search(regex)
Returns the index of the first match, or -1. Ignores the g flag.
str.replace(regex, replacement)
Replaces matched text with a new string or a function return value. Use $1 etc. to reference capture groups.
str.split(regex)
Splits a string at each match of the pattern — more flexible than splitting on a single fixed character.
JS — Method Examples
const email = "user@example.com";
const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// test() — validate
console.log(emailRe.test(email));  // true

// search() — find position
console.log("Hello World".search(/world/i));  // 6

// replace() — swap text  ($1 = first captured group)
const date = "2025-07-21";
console.log(date.replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1"));
// "21/07/2025"

// replaceAll equivalent using /g flag
const str = "foo bar foo baz foo";
console.log(str.replace(/foo/g, "qux"));  // "qux bar qux baz qux"

// split() — split on multiple separators at once
const csv = "one, two;three|four";
console.log(csv.split(/[,;|]\s*/));
// ["one", "two", "three", "four"]

// matchAll() — all matches with groups
const text = "#ff0000 and #00ff00";
for (const hit of text.matchAll(/#([a-f0-9]{6})/gi)) {
  console.log(hit[0], hit[1]);  // "#ff0000" "ff0000"  then "#00ff00" "00ff00"
}

Common Real-World Regex Patterns

These are patterns you'll reach for again and again in real projects:

JS — Patterns Cheat Sheet
// Email (simplified)
const emailRe   = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// URL (http & https)
const urlRe     = /https?:\/\/[\w\-.]+(\/[\w\-./?%&=]*)?/;

// Indian mobile number (+91 optional)
const mobileRe  = /^(\+91[\s-]?)?[6-9]\d{9}$/;

// Strong password (min 8 chars, upper, lower, digit, special)
const pwdRe     = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&]).{8,}$/;

// Hex color code (#fff or #ffffff)
const hexRe     = /^#([a-f0-9]{3}|[a-f0-9]{6})$/i;

// ISO date YYYY-MM-DD
const isoDateRe = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;

// Strip HTML tags from a string
const noTagsRe  = /<[^>]*>/g;
console.log("<b>Hello</b>".replace(noTagsRe, ""));  // "Hello"

// Trim extra whitespace
console.log("  hello   world  ".replace(/\s+/g, " ").trim());
// "hello world"
Note
The (?=...) syntax above is a lookahead assertion. (?=.*[A-Z]) means "the string must contain at least one uppercase letter somewhere" — without consuming any characters. Lookaheads are zero-width assertions that add conditions to a match without advancing the cursor.

Where Regex is Used in Real Projects

Regular expressions show up everywhere in production JavaScript code:

Form validation
Text search
Find & replace
Parsing / splitting
Syntax highlighting
URL routing
Log file parsing
Input sanitisation
Tokenisation/lexing
Markdown parsing
⚡
Free Resource
Download our JavaScript Cheat Sheet
Regex patterns, ES6+ syntax, built-in methods — all on one page.
Get Sheet
Advertisement

Try It Yourself — Regex Tester

Live Editor
✎ Editor
👁 Preview
Common Mistake
Forgetting to escape special regex characters like ., +, ?, (, ) when you want them to mean the literal character. Use a backslash: \. matches a real dot, while . matches any character.
Quick Check — Chapter 67

Which regex flag makes ^ and $ match the start and end of each line (not just the whole string)?

Chapter Summary
  • A Regular Expression is a pattern used to search, extract, or replace text in a string.
  • Create regex with literal syntax /pattern/flags or new RegExp(pattern, flags).
  • Key flags: g (all matches), i (case-insensitive), m (multiline), s (dot-all).
  • Character classes (\d, \w, [abc]) and quantifiers (+, *, {n,m}) build powerful patterns.
  • Capturing groups (...) and named groups (?<name>...) let you extract specific parts of a match.
  • Use test() to validate, match() / matchAll() to extract, replace() to transform, and split() to divide strings.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel