regexhelper
Test a pattern. Copy a ready-made one. No signup.

Regex to Extract the Domain from a URL

Copy the pattern, paste your URLs, and see the domain of each one highlighted in capture group 1. Below: how it skips http(s) and www.

/ /

What this pattern captures

Group 1 ([^/:?#]+) is the domain: everything after the scheme and optional www., up to the first slash, colon, question mark or hash. That stops it before the port, path, query and fragment.

Part by part

https?:// — matches http or https.

(?:www\.)? — an optional, non-capturing www. so it is stripped from the result.

([^/:?#]+) — the host itself, captured for extraction.

Getting the value in code

Use url.match(/https?:\/\/(?:www\.)?([^/:?#]+)/i)[1]. In a browser you can also use the built-in new URL(url).hostname, which is more robust for edge cases.

FAQ

Does it keep the www prefix?

No. The (?:www\.)? group is non-capturing and optional, so group 1 returns the bare domain without www.

What about the port number?

The character class [^/:?#] stops at the colon, so a :8080 port is excluded from the captured domain.

Should I just use new URL()?

In JavaScript, new URL(str).hostname is the most reliable way to get a host. Use the regex when you must scan free text for many URLs at once.