SPONSOR: Cloud Hosting for Developers • Scale your apps globally with zero configuration. [Ad Placement Zone]

URL Validation Regex

A comprehensive reference and playground for testing URL-matching regular expressions. Match protocols, domain sub-levels, file paths, and query parameters.

Loading editor...

Anatomy of a URL Validation Regex

Web URLs consist of multiple optional and required sections. A standard regular expression for general web URL validation looks like this:

/^(https?:\/\/)?(www\.)?([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(\/[a-zA-Z0-9\-._~:/?#[\]@!$&'()*+,;=]*)?$/

Here is a breakdown of how the pattern parses each block:

  • Protocol (^(https?:\/\/)?): Matches either http:// or https://. The trailing question mark makes the entire group optional.
  • Subdomain ((www\.)?): Matches the literal string www. optionally.
  • Domain Name (([a-zA-Z0-9-]+\.)+): Matches the domain name segment followed by a dot, permitting nested levels (e.g. blog.dev.site.com).
  • Extension ([a-zA-Z]{2,}): Validates the top-level extension (like .com or .org).
  • Path & Query ((\/[a-zA-Z0-9\-._~:/?#[\]@!$&\'()*+,;=]*)?): Matches slash characters followed by any URL-safe characters, representing folder paths, filenames, queries (?q=1), or anchors (#top).

Escaping Forward Slashes

In JavaScript, regular expression literals are bound by forward slashes (/pattern/). Because of this, any literal slash character inside your expression must be escaped with a backslash (\/) to prevent the parser from thinking the expression has ended early.

For example, matching a URL path prefix like /api/v1/ requires writing \/api\/v1\/. Failing to escape forward slashes is one of the most frequent syntax compilation failures.