Skip to article content
FrontendXLesson 11 / 30

Regular Expressions

Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.

intermediate · about 40 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Read and write a pattern with the right flags for the task.
  • Use test, exec, match, replace and split without state bugs.
  • Escape user input before building a dynamic pattern.

Overview

#

Literals and flags

A regular expression is written as a literal between slashes or built with the RegExp constructor. Flags change matching: g finds all matches, i ignores case, m makes anchors match per line, s lets the dot match newlines and u enables full Unicode handling. Prefer the literal form when the pattern is fixed so it is compiled once.

Methods and their return shapes

test returns a boolean. exec returns a match array with an index and capture groups, or null. String methods reuse the same engine: match, matchAll, replace, replaceAll, search and split. When a pattern has the g flag, exec and test keep a lastIndex cursor, so the same regex object can behave differently on repeated calls.

snippet.js
const digits = /\d/g;
console.log('a1b2'.replace(digits, '#')); // a#b#
console.log('a1b2'.match(/\d/g)); // ['1', '2']

Groups, greediness and escaping

Parentheses capture, and named groups use the ?<name> syntax so results read clearly. Quantifiers are greedy by default and consume as much as possible; a trailing question mark makes them lazy. Backtracking can explode on nested quantifiers, so keep patterns specific. Always escape user input before inserting it into a pattern, because characters such as the dot and the plus become operators.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    What does this line print?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    console.log('a1b2'.replace(/\d/g, '#'), 'a1b2'.match(/\d/g).length);
    Choose the best answer
  2. Exercise 2Explain

    Explain the difference between a greedy quantifier and a lazy one.

    starter.text
    console.log('<a><b>'.match(/<.+>/)[0], '<a><b>'.match(/<.+?>/)[0]);

    Reveal the reference answer
    reference.text
    A greedy quantifier consumes as much as it can while still allowing the rest of the pattern to match, so <.+> spans from the first angle bracket to the last one. A lazy quantifier, written with a trailing question mark, consumes as little as possible, so <.+?> stops at the first closing bracket.

    Authored expected output: <a><b> <a>

    Greediness controls how far the engine advances before backtracking. Lazy matching is the usual choice when you want the shortest span.

  3. Exercise 3Implement

    Implement `escapeRegExp(text)` so it escapes every character that has special meaning in a pattern. Running `console.log(escapeRegExp('a.b*c'))` should print `a\.b\*c`.

    starter.javascript
    function escapeRegExp(text) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    function escapeRegExp(text) {
      return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }

    Authored expected output: a\.b\*c

    The character class lists every metacharacter, and the replacement prefixes each match with a backslash. This is required before inserting user text into a pattern.

  4. Exercise 4Debug

    This loop reuses one global regex and prints an alternating result. Find and fix the bug so every iteration prints true.

    starter.javascript
    const re = /\d/g;
    for (let i = 0; i < 3; i++) {
      console.log(re.test('1'));
    }

    Reveal the reference answer
    reference.javascript
    for (let i = 0; i < 3; i++) {
      console.log(/\d/.test('1'));
    }

    Authored expected output: true true true

    A global regex keeps a lastIndex cursor between calls. The first test matches at index 0 and advances lastIndex to 1. The second test starts at the end of '1', finds nothing, returns false and resets lastIndex to 0. The third test matches again, so the loop prints true, false, true. Removing g or creating the regex per call keeps the result consistently true.

  5. Exercise 5Test

    Write assertions that prove named groups and the u flag behave as expected.

    starter.javascript
    function assertEqual(actual, expected, label) {
      if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual);
    }

    Reveal the reference answer
    reference.javascript
    const m = /(?<year>\d{4})-(?<month>\d{2})/.exec('2026-11');
    assertEqual(m.groups.year, '2026', 'named year group');
    assertEqual(m.groups.month, '11', 'named month group');
    assertEqual(/^.$/u.test('\u{1F600}'), true, 'u flag matches a full code point');
    console.log('all assertions passed');

    Authored expected output: all assertions passed

    Named groups are exposed on the groups object of the match. The u flag makes the dot and quantifiers operate on code points, so a single emoji counts as one character.

  6. Exercise 6Interview

    Would you validate an email address with one large regular expression?

    Reveal the reference answer
    reference.text
    I would use a deliberately simple pattern to catch obvious mistakes and rely on a confirmation email for real verification, because a fully correct address grammar is far more permissive than most people expect and a giant regex is hard to maintain and can backtrack badly. I keep the pattern readable, anchor it, and never treat a regex pass as proof that the address exists.

    The answer should weigh correctness and maintainability over cleverness, and should separate format checks from deliverability checks.

Common misconceptions

#
  • A global regex can be reused with test without side effects.
  • The dot matches every character including newlines.
  • Building a pattern from user input needs no escaping.

Follow-up practice

#
  • javascript-foundations-testing-javascript
  • javascript-foundations-strings-and-unicode

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.