URL Regex Pattern
The pattern above matches HTTP and HTTPS URLs, including paths, query strings, and fragments. It rejects ftp:// schemes and bare strings with no protocol. Of the test strings above, it matches https://example.com, the devbento tool URL, the localhost API with query params, and the subdomain URL with a fragment. It does not match ftp://not-http.com or the plain text string.
Pattern Breakdown
| Segment | Pattern | What it matches |
|---|---|---|
| Protocol | https?:\/\/ | http:// or https:// |
| Host | [\w\-]+(\.[\w\-]+)+ | Domain name with at least one dot (e.g. example.com, sub.domain.co.uk) |
| Path, query, fragment | ([\w.,@?^=%&:/~+#\-]*[\w@?^=%&/~+#\-])? | Optional path and query string, must not end on a punctuation character |
The trailing character class is intentionally non-anchored at the end. The second character class inside the group ([\w@?^=%&/~+#\-]) ensures the match does not stop on a trailing period or comma, which avoids capturing punctuation that follows a URL in prose (e.g. “visit https://example.com, then…”).
The URL Constructor as a Validation Alternative
For JavaScript, new URL(input) is the most reliable way to check whether a string is a valid absolute URL:
function isValidUrl(str) {
try {
const url = new URL(str);
return url.protocol === 'http:' || url.protocol === 'https:';
} catch {
return false;
}
}
This handles edge cases the regex does not: IPv6 addresses (http://[::1]:8080/), internationalized domain names after Punycode normalization, and percent-encoded characters in paths. The protocol check filters out javascript:, data:, and other schemes you probably do not want to accept.
Edge Cases the Pattern Does Not Cover
URLs with authentication credentials (http://user:pass@example.com) are not matched because the @ in the userinfo portion confuses the host parsing. URLs with IPv6 addresses (http://[2001:db8::1]/) require bracket handling that adds significant complexity. Unicode domain names (https://münchen.de) must first be converted to Punycode (https://xn--mnchen-3ya.de) before the pattern matches them.
For a production system handling user-submitted URLs, the pattern on this page works well as a first filter, but pass survivors through the URL constructor before storing or fetching.
Extracting URLs from Text
The most practical use of a URL regex is extracting links from logs, markdown, or plain text. When doing this with the g flag, watch for two gotchas: markdown link syntax ([label](https://url)) will include the closing ) in the match, and HTML href attributes may have the URL wrapped in quotes. A post-processing step to strip trailing ), ", or ' covers most of these cases.
If you need to encode URLs before embedding them in HTML or a query string, the URL Encoder handles percent-encoding for you.