easy +8 pts

Extract domain from URL

Parse URLs and pull out the clean domain name.

Write a function `extract_domain(url)` that takes a URL string and returns the domain name. The domain name is defined as the hostname without the port (if present) and without the leading 'www.' part. The URL may include a scheme (http://, https://), and may include a path, query string, or fragment. All URLs are valid and use only lowercase letters. Specifically: - Remove the scheme if present (anything before '://'). - If the remaining string contains a colon followed by a port number, remove the port. - If the hostname starts with 'www.', remove that prefix. - Ignore everything after the first '/' (the path), also ignore '?' or '#' if they appear without a slash. - The function should return the resulting domain string. Example: - `extract_domain('https://www.example.com/path')` returns `'example.com'`. - `extract_domain('http://sub.domain.org:8080?a=1')` returns `'sub.domain.org'`. Implement the function in Python.

Constraints

Input URL length is between 1 and 200 characters. The input is a valid URL with a scheme and hostname. The hostname is composed of alphanumeric characters and dots. The port (if present) is a positive integer. Output length is between 1 and 200 characters. Time complexity should be O(n), where n is the length of the URL.

Example

>>> extract_domain('https://www.example.com/path')
'example.com'
>>> extract_domain('http://sub.domain.org:8080?a=1')
'sub.domain.org'
>>> extract_domain('https://example.co.uk')
'example.co.uk'
8 points ~12 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

First split on '://' to remove the scheme.
Then split on the first '/' or '?' or '#' to isolate the host:port part.
Remove the port by splitting on ':'.
Finally, strip the leading 'www.' if present.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.