Parse a URL into its parts in JavaScript
Intermediate · 3 min read
A web address carries a lot of information: which site, which page, which search filters, which spot on the page. Analytics tools, routers, link checkers and "share this page" buttons all need to pull a URL apart into those pieces.
In this tutorial you will write parseUrl, which breaks a URL into its parts and returns null for text that isn't a URL. You will use the built-in URL class instead of writing your own pattern. You need to know objects, functions and try...catch.
The parts of a URL
Take this address:
https://www.example.com:8080/routes/lagos?from=Ojota&to=Abuja#seats
https:is the protocol, how to talk to the server.www.example.comis the hostname, which server.8080is the port, a numbered door on that server. It is usually left out./routes/lagosis the pathname, which page.?from=Ojota&to=Abujais the search or query string: extra settings askey=valuepairs.#seatsis the hash, a spot within the page.
The URL class
new URL(text) reads the address and gives you an object with each part ready to use. It is built into browsers and Node, and it already knows every odd rule, like escaped spaces. Writing a regular expression for URLs is a trap: there are too many optional parts.
Here is the exercise. Try it yourself first if you like, then read on and we will build it.
12 Parse a URL
fairBreak a URL into its parts. Use the built-in parser rather than a regular expression, and handle a bad URL without throwing at the caller.
Stuck? Three hints, smallest first
- 1.
new URL(str)does the whole job, in Node and in browsers. - 2. It throws on an invalid URL, so wrap it or use
URL.canParse. - 3.
searchParamshandles the query string, including repeated keys.
Step 1: read the parts
const url = new URL('https://www.example.com:8080/routes/lagos?from=Ojota&to=Abuja#seats');
console.log(url.protocol); // https:
console.log(url.hostname); // www.example.com
console.log(url.host); // www.example.com:8080
console.log(url.port); // 8080
console.log(url.pathname); // /routes/lagos
console.log(url.search); // ?from=Ojota&to=Abuja
console.log(url.hash); // #seats
Look closely at the details. protocol keeps its colon. search keeps its ? and hash keeps its #. hostname has no port, while host includes it. And port is a string, '8080', not a number.
Step 2: read the query string
url.searchParams understands the key=value pairs. Object.fromEntries turns them into a plain object:
console.log(url.searchParams.get('from')); // Ojota
console.log(Object.fromEntries(url.searchParams)); // { from: 'Ojota', to: 'Abuja' }
It also decodes escaped characters. %20 is how a URL writes a space:
console.log(new URL('https://x.com/?city=Port%20Harcourt').searchParams.get('city')); // Port Harcourt
Step 3: the wrong turn with bad input
What if the text isn't a URL?
try { new URL('not a url'); } catch (e) { console.log(e.constructor.name); } // TypeError
new URL throws. If parseUrl let that error escape, every caller would need its own try...catch. So the answer catches it once and returns null, which means "no result".
Step 4: put it in a function
function parseUrl(input) {
let url;
try { url = new URL(input); } catch { return null; }
return {
protocol: url.protocol,
hostname: url.hostname,
host: url.host,
port: url.port,
pathname: url.pathname,
search: url.search,
hash: url.hash,
query: Object.fromEntries(url.searchParams),
};
}
console.log(parseUrl('https://www.example.com:8080/routes/lagos?from=Ojota&to=Abuja#seats').query); // { from: 'Ojota', to: 'Abuja' }
console.log(parseUrl('not a url')); // null
Step 5: defaults you should know
console.log(JSON.stringify(parseUrl('https://example.com/').port)); // ""
console.log(JSON.stringify(parseUrl('https://example.com').pathname)); // "/"
console.log(JSON.stringify(parseUrl('https://example.com/').hash)); // ""
JSON.stringify puts quotes around the strings so you can see an empty one. When the port is the protocol's usual one, port is empty, not '443'. The pathname is never empty: it is at least /. A missing hash is an empty string.
Addresses without a protocol are not URLs to the parser:
console.log(parseUrl('example.com/path')); // null
console.log(parseUrl('/routes/lagos')); // null
console.log(new URL('/routes/lagos', 'https://example.com').href); // https://example.com/routes/lagos
A path on its own works if you give new URL a second argument, the base address to start from.
Step 6: repeated keys
A query string can repeat a key, as in ?tag=a&tag=b. Object.fromEntries keeps only the last one:
const repeated = new URL('https://x.com/?tag=a&tag=b');
console.log(Object.fromEntries(repeated.searchParams)); // { tag: 'b' }
console.log(repeated.searchParams.getAll('tag')); // [ 'a', 'b' ]
Use getAll when a key can appear more than once, like filters on a shop page.
The full solution
The panel parses the sample address and prints the whole result, then the default port and pathname, the invalid input, and the repeated query key. Press Run to see each part.
function parseUrl(input) {
let url;
try { url = new URL(input); } catch { return null; } // invalid: say so, do not throw
return {
protocol: url.protocol, // includes the ':'
hostname: url.hostname, // no port
host: url.host, // with port, if any
port: url.port, // '' when default for the protocol
pathname: url.pathname,
search: url.search,
hash: url.hash,
query: Object.fromEntries(url.searchParams),
};
}
const sample = 'https://www.example.com:8080/routes/lagos?from=Ojota&to=Abuja#seats';
const parsed = parseUrl(sample);
console.log(parsed);
console.log('--- defaults and edge cases ---');
console.log("port when default :", JSON.stringify(parseUrl('https://example.com/').port), '<- empty, not 443');
console.log('pathname when absent:', JSON.stringify(parseUrl('https://example.com').pathname), '<- always at least /');
console.log('invalid input :', parseUrl('not a url'));
console.log('--- repeated query keys ---');
const repeated = new URL('https://x.com/?tag=a&tag=b');
console.log('fromEntries keeps the last:', Object.fromEntries(repeated.searchParams));
console.log('getAll keeps both :', repeated.searchParams.getAll('tag'));
Output
18 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 18 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the protocol includes its colon', parsed.protocol, 'https:');
test('the hostname has no port', parsed.hostname, 'www.example.com');
test('the host does', parsed.host, 'www.example.com:8080');
test('the port is a string', parsed.port, '8080');
test('the pathname', parsed.pathname, '/routes/lagos');
test('the search string includes the question mark', parsed.search, '?from=Ojota&to=Abuja');
test('the hash includes the hash sign', parsed.hash, '#seats');
test('the query is parsed into an object', parsed.query, { from: 'Ojota', to: 'Abuja' });
test('a default port comes back empty, not 443', parseUrl('https://example.com/').port, '');
test('the pathname is always at least a slash', parseUrl('https://example.com').pathname, '/');
test('a missing hash is an empty string', parseUrl('https://example.com/').hash, '');
test('invalid input gives null instead of throwing', parseUrl('not a url'), null);
test('a protocol-less string is invalid to the URL parser', parseUrl('example.com/path'), null);
test('a relative path is invalid on its own', parseUrl('/routes/lagos'), null);
test('but works with a base', new URL('/routes/lagos', 'https://example.com').href, 'https://example.com/routes/lagos');
test('fromEntries keeps only the last of a repeated key', Object.fromEntries(new URL('https://x.com/?tag=a&tag=b').searchParams), { tag: 'b' });
test('getAll keeps both', new URL('https://x.com/?tag=a&tag=b').searchParams.getAll('tag'), ['a', 'b']);
test('the parser decodes percent-escapes', new URL('https://x.com/?city=Port%20Harcourt').searchParams.get('city'), 'Port Harcourt');
new URL() is the answer, and writing a regex for this is a mistake — URLs have too many optional parts and too much escaping. Three behaviours to remember: the port is '' when it is the protocol default (not '443'), the pathname is never empty (always at least /), and a string with no protocol is simply not a URL, so 'example.com/path' fails unless you supply a base.
The repeated-key assertions are the sharp edge. Object.fromEntries(searchParams) is convenient and it silently discards all but the last value of a repeated key, so ?tag=a&tag=b becomes { tag: 'b' }. Use getAll when a key can legitimately repeat.
Common mistakes
- Writing a regular expression for URLs. It will miss ports, escapes or empty parts. Use
new URL. - Expecting
portto be a number, or'443'. It is a string, and empty when the port is the default. - Using
fromEntrieson repeated keys. All but the last value are lost. UsegetAll.
Try it yourself
- Use
URL.canParse(text)to writeisUrl(text)withouttry...catch. - Add a
?page=2to a URL withurl.searchParams.set('page', '2')and printurl.href. - Change
parseUrlsoqueryholds an array for every key, usinggetAll.