JavaScript: How to get the URL parts from a URL

1 min read
Table of contents

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
0
Subscribe to my newsletter
Read articles from Hari Krishna Anem directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Hari Krishna Anem
Hari Krishna Anem
Full stack developer (ReactJS, NodeJS, JavaScript, PHP, SQL)