Skip to main content

Command Palette

Search for a command to run...

JavaScript: How to get the URL parts from a URL

Published
1 min read
JavaScript: How to get the URL parts from a URL
H

Full stack developer (ReactJS, NodeJS, JavaScript, PHP, SQL)

const url = new URL('http://example.com:12345/blog/foo/bar?startIndex=1&pageSize=10');
const { protocol, hostname, port, pathname, search } = url;

console.log('protocol =>', protocol);
console.log('hostname =>', hostname);
console.log('port =>', port);
console.log('pathname =>', pathname);
console.log('Query parameters =>', search);
console.log('Get query parameter values =>' , url.searchParams.get('startIndex'), url.searchParams.get('pageSize'))
Output:
protocol => http:
hostname => example.com
port => 12345
pathname => /blog/foo/bar
Query parameters => ?startIndex=1&pageSize=10
Get query parameter values => 1 10

Execute above code here

More from this blog

E

Everyday Dev Patterns

26 posts

A collection of real-world JavaScript snippets, patterns, and gotchas from my day-to-day work.