Web

URL Regex: Practical HTTP and HTTPS Examples

URLs contain many details. Regex works well for controlled exercises and searches, but full production parsing is often better handled by native URL APIs.

Before you start: test every pattern with examples that should match and examples that should fail.

A teaching pattern

This example accepts HTTP or HTTPS, a simple hostname, and an optional path.

Regex: ^https?:\/\/[\w.-]+\.[A-Za-z]{2,}(?:\/.*)?$

Why https? works

The ? makes the preceding s optional, so both http and https are accepted.

Real URLs are more complicated

Ports, IPv6, query strings, fragments, Unicode domains, and hostname rules can turn a universal URL Regex into a maintenance problem.

Use URL APIs for parsing

In JavaScript, new URL(value) gives you protocol, hostname, pathname, and query data directly. Regex remains useful for targeted searching and restrictions.

Next step: test it for real

Use the Playground to experiment with the pattern, then practice in the game with feedback on false positives and false negatives.

Practice in the gameTest in Playground

Keep learning

← Back to learning hub