Chapter 26 of 28 · JavaScript for Beginners — Complete Free Tutorial

Regular Expressions in JavaScript

Regular expressions (regex) are a compact language for describing text patterns — find, validate, extract, replace. From email checks to log parsing, regex is one of the most concentrated powers in the language: a one-line pattern can do what takes twenty lines of string code. This chapter teaches the syntax you will use daily and the traps to avoid.

Two ways to create a regex

const re1 = /abc/g;              // literal — parsed at load time
const re2 = new RegExp('abc', 'g'); // dynamic — needed when the pattern is built at runtime

console.log('xxabc'.includes('abc'));   // string method also accepts patterns:
console.log('xxabc'.search(/abc/));     // → 2

Flags

FlagMeaning
gGlobal — all matches, not just the first
iCase-insensitive
mMultiline — ^/$ match line breaks too
sDot-all — . also matches newlines
uUnicode-aware (correct handling of emoji etc.)

test and exec

console.log(/\d{3}/.test('abc123'));   // → true  (three digits exist)

const m = /(\d+)-(\d+)/.exec('order 42-7');
console.log(m[0]);   // → '42-7'  (whole match)
console.log(m[1]);   // → '42'    (first group)
console.log(m[2]);   // → '7'

Core pattern syntax

SyntaxMatches
.Any single character (except newline)
\d / \DDigit / non-digit
\w / \WWord char (letter, digit, _) / other
\s / \SWhitespace / non-whitespace
^ / $Start / end of input (string anchors)
\bWord boundary
[abc] / [^abc]Character set / negated set
a|bEither pattern
+ * ?1+ / 0+ / 0-1 repetitions
{2,4}2 to 4 repetitions
(…)Capture group (numbered, reusable)
(?:…)Non-capturing group (grouping without a backreference)

Practical patterns

// digits anywhere
'42 items'.match(/\d+/);              // → ['42']

// starts with, ends with
/^[A-Z]/.test('Hello');               // → true (capital first letter)
/\.(png|jpg|svg)$/i.test('logo.PNG'); // → true

// word count
'one two three'.match(/\S+/g);        // → ['one','two','three']

// strip non-digits (phone formatting)
'call: +1 (555) 123-4567'.replace(/\D+/g, '');   // → '15551234567'

// capture + replace with $1
'2026-03-05'.replace(/(\d{4})-(\d{2})-(\d{2})/, '$3/$2/$1');  // → 05/03/2026

match, matchAll, replaceAll

const text = 'a1 b2 c3';

console.log(text.match(/\w\d/g));                 // → ['a1','b2','c3'] (g flag required for all)
console.log([...text.matchAll(/(\w)(\d)/g)]);     // array of full match objects

console.log(text.replaceAll(/\s/g, '-'));         // → 'a1-b2-c3'

Validation with the test method

const isEmail = (v) => /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v);
const isPhoneIN = (v) => /^[6-9]\d{9}$/.test(v);      // 10 digits starting 6–9
const hasStrongPass = (v) => v.length >= 8 && /\d/.test(v) && /[A-Z]/.test(v);

console.log(isEmail('a@b.co'));   // → true
console.log(isEmail('nope'));     // → false

Honesty note: no single regex validates emails fully (the spec is enormous). Use a pragmatic pattern for format, then send a confirmation email for existence — the pattern only gates obvious typos.

Groups for structured extraction

const log = '2026-03-05 14:22 ERROR disk full';
const m = log.match(/^(\S+) (\S+) (\w+) (.+)$/);
console.log(m[1], m[3], m[4]);
// → 2026-03-05 ERROR disk full

Named groups (readability)

const url = '/tutorials/css-for-beginners/box-model';
const { groups } = url.match(/\/(?<tutorial>[^/]+)\/(?<chapter>[^/]+)/) ?? {};
console.log(groups?.tutorial, groups?.chapter);
// → css-for-beginners box-model

Performance and safety

  • Catastrophic backtracking — nested quantifiers like (a+)+b can hang on near-misses; keep patterns simple, test against adversarial input (e.g., 50 as).
  • Compile once, reuse: const RE = /…/g at module scope (and reset lastIndex with g when reusing across calls — or create fresh per call).
  • Regex is not a parser — HTML, JSON and full grammars deserve real parsers.
  • Readability beats cleverness — a complex pattern deserves a comment and a unit test.

When NOT to use regex

  • Simple containment → includes / startsWith.
  • Splitting known separators → split(',').
  • Parsing HTML → DOM APIs (HTML entities and markup rules are a job for the parser).

Common mistakes

  • Missing g in match — returns only the first match.
  • Forgetting anchors — /\d+/ matches digits anywhere; /^\d+$/ matches only digits for the whole string (the validation classic).
  • Escaping literals — .+*?^$()[]{} are special; escape with \ when you mean the literal character.
  • Reuse of /g regex state — lastIndex persists between test/exec calls, causing alternating results.
  • Validation over-reach — regex checks format, not business rules (server still validates).

Practice checklist

  1. Write isSlug(s): lowercase letters, digits and single hyphens, 3–50 chars.
  2. Extract all dates from a text blob with matchAll and reformat them with groups.
  3. Mask a credit-card-like number: keep last 4 digits (replace(/\d(?=\d{4})/g, '*') — then explain every part).
  4. Prove the anchoring rule: compare /\d/ and /^\d+$/ against '12a'.

Text is handled — next, the other data workhorses: Dates, Math & Numbers.

Quiz: Regular Expressions in JavaScript

5 questions · 70% to pass

Frequently Asked Questions

JavaScript is the programming language of the web. It adds behaviour to pages: responding to clicks and input, validating forms, fetching data from APIs, updating the DOM without reloading, and much more. It also runs on servers (Node.js), in desktop and mobile apps, and in build tooling.

They are unrelated languages that share a similar name for historical marketing reasons. Java is a statically-typed compiled language; JavaScript is a dynamically-typed interpreted language designed for the browser. Knowing one does not imply knowledge of the other.

Helpful but not mandatory — HTML gives you the structure JavaScript manipulates and CSS the styling it toggles. If you know basic tags, classes and selectors, you have enough to start; the DOM chapters assume only that much.

Use const by default and let when the value must change. Avoid var entirely in modern code: it is function-scoped instead of block-scoped, hoists differently, and can create accidental globals. This course uses const and let throughout.

The Document Object Model is the browser’s in-memory tree of objects representing your HTML. JavaScript reads and modifies that tree — selecting elements, changing text, adding nodes, attaching event listeners — and the browser re-renders the page to match.

== compares after converting types (so 5 == "5" is true), while === requires the same value AND the same type (5 === "5" is false). Loose equality has famously confusing rules — use === and !== everywhere unless you have a specific reason not to.

JavaScript is single-threaded, so long-running work (timers, fetches, events) is handled by the browser and its callbacks are queued. The event loop moves queued callbacks onto the call stack only when it is empty, with promise callbacks (microtasks) taking priority over timers. It is why asynchronous code never freezes the page.

A Promise is an object representing a future value — pending, fulfilled or rejected — that can be chained and combined (Promise.all). async/await is syntax sugar over promises that lets asynchronous code read top-to-bottom with ordinary try/catch error handling.

Yes. Frameworks are built on exactly these fundamentals — components are functions, state is your variable discipline, effects are events, rendering is DOM work. Developers who learn vanilla first understand what the framework is doing and debug far faster.

Type out the examples instead of copying, build small end-to-end projects (expense tracker, weather app, quiz), handle every UI state (loading, empty, success, error), and revisit fundamentals while reading real code. Consistency beats volume — a little most days outpaces occasional marathons.