Token-by-token breakdown
| Token | Meaning | Example |
|---|---|---|
^ |
Anchor: asserts the position at the start of the string | Start of string |
( |
Start of a non-capturing group (implicit in JS) | N/A |
https? |
Literal 'http' followed by an optional 's' | http or https |
:// |
Literal colon followed by two forward slashes | :// |
)? |
End of group, quantifier: makes the entire group optional (0 or 1 times) | Optional 'http://' or 'https://' |
( |
Start of a non-capturing group (implicit in JS) | N/A |
www\. |
Literal 'www.' (dot is escaped) | www. |
)? |
End of group, quantifier: makes the entire group optional (0 or 1 times) | Optional 'www.' |
[a-zA-Z0-9-]+ |
Character class: one or more alphanumeric characters or hyphens | example, 123, test-site |
( |
Start of a capturing group | N/A |
\. |
Literal dot (escaped) | . |
[a-zA-Z0-9-]+ |
Character class: one or more alphanumeric characters or hyphens | com, org, site-name |
)+ |
End of group, quantifier: one or more repetitions of the group (greedy) | .com, .org, .site-name |
( |
Start of a capturing group | N/A |
[/?] |
Character class: either a forward slash or a question mark | / or ? |
.* |
Any character (except newline) zero or more times (greedy) | /path, ?query=1 |
)? |
End of group, quantifier: makes the entire group optional (0 or 1 times) | Optional path or query |
$ |
Anchor: asserts the position at the end of the string | End of string |
Matches
http://example.comhttps://www.example.com/pathexample.orgwww.test-site.com?query=1https://sub.domain.co.uk/path/to/page
Does not match
ftp://example.comexample..comhttp://exampleexample.com/path?query=1#fragmenthttp://example.com/path with space
Common pitfalls
- Overly permissive character class ([a-zA-Z0-9-]) allows invalid domain names (e.g., starting/ending with hyphen).
- Missing validation for top-level domains (e.g., '.com' is valid, but '.c' is not).
- Greedy quantifiers (+, *) may cause catastrophic backtracking with malformed input.
- Does not validate internationalized domain names (IDNs).
- Allows paths with spaces or special characters that may not be URL-encoded.
Performance notes
The pattern is generally efficient for typical URLs, but the greedy quantifiers (+, *) could lead to catastrophic backtracking with malformed input (e.g., long strings of dots or slashes). Anchoring (^ and $) ensures the entire string is validated, preventing partial matches. Consider using possessive quantifiers or atomic groups (if supported) to mitigate backtracking risks.