Course contentsShow
← JavaScript
Lesson 1730 of 2,72336. Regular ExpressionsFree lesson

Common Pattern: URL Matching

Creating regex patterns to match and extract components from URLs.

Common Pattern: URL Matching

You'll learn: How to create regex patterns that match and extract components from URLs like protocol, domain, path, and query parameters.

Understanding URL Structure

URLs have a predictable structure: protocol://domain:port/path?query#hash. Just as email validation uses a pattern to verify structure, URL matching uses regex to identify valid URLs and extract their parts. Think of it like parsing an address: you want to identify the street (domain), apartment number (port), and directions (path).

Basic URL Pattern

A simple URL matcher might look like:

const urlPattern = /https?:\/\/[\w.-]+\.[a-z]{2,}(\/[^\s]*)?/i;

urlPattern.test('https://example.com'); // true
urlPattern.test('http://site.co.uk/path'); // true
urlPattern.test('ftp://wrong.com'); // false (only http/https)

Breaking it down:

  • https? matches "http" or "https"
  • :\/\/ matches "://" (escaped slashes)
  • [\w.-]+ matches subdomain/domain parts
  • \.[a-z]{2,} matches the TLD (.com, .org, etc.)
  • (\/[^\s]*)? optionally matches path (slash + non-whitespace)

Extracting URL Components

Use capture groups to extract parts:

const detailedPattern = /^(https?):\/\/([\w.-]+)(\.[a-z]{2,})(\/[^\s?]*)?(\?[^\s#]*)?(#.*)?$/i;
const match = 'https://api.site.com/users?id=5#top'.match(detailedPattern);

if (match) {
  const [, protocol, domain, tld, path, query, hash] = match;
  console.log({ protocol, domain, path, query, hash });
}

Practical Considerations

URL regex can get complex quickly. For production use, consider the built-in URL constructor for parsing rather than regex for validation, but regex remains useful for finding URLs in text or basic pattern checking.

Key Takeaway: URL matching with regex identifies protocol, domain, and path patterns using character classes and optional groups, though complex parsing is better handled by JavaScript's URL API.