Developer
Encoders, converters & dev utilities
Regex to Match a URL (HTTP / HTTPS)
A practical pattern for matching an http or https URL is ^https?://[^\s/$.?#].[^\s]*$ — the literal http, an optional s, ://, then a non-empty host that does not start with a special character, followed by any run of non-whitespace characters. It accepts https://a.com and http://x.io/p?q=1 while rejecting an ftp URL, a bare "http://" with no host, or a string with spaces. Like every real-world URL regex, this is a loose match: URLs are governed by a detailed grammar (RFC 3986) that is painful to encode fully in a regular expression, and different tools draw the line differently. For genuine validation and parsing you should prefer the built-in URL constructor (new URL(str)), which throws on malformed input and gives you the parsed parts. This JavaScript pattern is verified in CI against real examples and counter-examples. Copy it, test your own strings in the live in-browser tester. Free, no login.
Pattern: ^https?://[^\s/$.?#].[^\s]*$ (loose http/https matcher)
- Matches: https://a.com and http://x.io/p?q=1
- Rejects: ftp://a.com, "not a url" and http:// (no host)
- For real validation and parsing, prefer the URL constructor: new URL(str)
- The https? makes the s optional, matching both http and https
Frequently asked questions
What is a simple regex to match a URL?
A commonly used one is ^https?://[^\s/$.?#].[^\s]*$. The https? matches http or https, :// is literal, [^\s/$.?#] requires a real first host character (not a slash, dot, query or fragment marker), and [^\s]* allows the rest of the URL with no whitespace. It accepts https://a.com and http://x.io/p?q=1 and rejects ftp URLs, plain text, or an empty host. It is intentionally loose rather than a full RFC 3986 grammar.
Should I validate URLs with regex or the URL constructor?
For anything beyond a quick shape check, use the URL constructor: new URL(str) parses the string and throws a TypeError if it is not a valid URL, and it gives you the protocol, host, pathname and query already split out. A regex is fine to filter obvious non-URLs in a text field, but it cannot fully and correctly implement the URL specification. Use the regex as a first pass and the URL constructor for authoritative validation and parsing.