WORKED EXAMPLE / ECMASCRIPT

HTTP and HTTPS URL regex

A conservative web URL check for HTTP(S), dotted hostnames, and an optional path, query, or fragment.

Pattern

^https?:\/\/(?:www\.)?[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z]{2,})+(?:[/?#][^\s]*)?$
Flavor
JavaScript (ECMAScript)
Flags
Flags: i

What it does

This pattern is useful when a product deliberately accepts only ordinary public-looking HTTP and HTTPS URLs. It keeps the scheme explicit and prevents hostname labels from starting or ending with a hyphen.

Token-by-token explanation

  1. ^

    Starts matching at the beginning of the URL.

  2. https?

    Requires http and permits one optional s for HTTPS.

  3. :\/\/

    Requires the literal :// scheme separator.

  4. (?:www\.)?

    Optionally accepts a leading www. hostname label.

  5. [a-z0-9]

    Starts the first hostname label with a letter or digit.

  6. (?:[a-z0-9-]*[a-z0-9])?

    Completes the first hostname label while ensuring a hyphen is not its final character.

  7. (?:\.[a-z]{2,})+

    Requires one or more dotted alphabetic domain segments of at least two characters.

  8. (?:[/?#][^\s]*)?

    Optionally accepts a path, query, or fragment beginning with /, ?, or # and containing no whitespace.

  9. $

    Stops matching at the end of the URL.

Test strings

Matches

  • https://example.com
  • http://www.docs.example.co.uk/path?q=regex#tokens

Does not match

  • ftp://example.com
  • https://-example.com

Common mistakes

  • Using a URL regex to prevent server-side request forgery instead of resolving and enforcing an explicit network allow-list.
  • Making the scheme optional when the application requires an absolute navigable URL.

Limitations

  • It intentionally excludes valid URLs such as localhost, IP-address hosts, ports, Unicode domains, and many percent-encoded or uncommon hostname forms; URL parsing and allow-listing are safer for security decisions.