logo
post image

Reading a URL and its Parts with Javascript

Use-Cases of this Tutorial

  • Read a given URL and find out its components - domain, path, query parameters etc.

Reading a URL and getting information about its various components — hostname, path, parameters etc is one of the common things required in Javascript. This tutorial tells how we can read any url, and get its component parts.

Concepts and Methods Involved

The URL object is the Javascript interface that can read urls. The URL works like a class — we need to create a new URL object whenever we need to read a url.

A new URL object can be instantiated from the current page url, or from a given string referenced in code.

// creating new URL object from the current url
var url = new URL(document.URL);
// creating new URL object from a string
var url = new URL('https://usefulangle.com/post/78/javascript-get-url-parameters');

Getting the URL Protocol

The protocol of the URL can be found with the protocol property. Note that it includes the final : also.

var post_url = new URL('https://usefulangle.com/post/78/javascript-get-url-parameters');

// "https:"
console.log(post_url.protocol);

Getting the URL HostName

The hostname in the URL can be found with the hostname property.

var post_url = new URL('https://usefulangle.com/post/78/javascript-get-url-parameters');

// "usefulangle.com"
console.log(post_url.hostname);

Getting the URL Pathname

The pathname property gives the full path of the url. The initial / is also included.

var post_url = new URL('https://usefulangle.com/post/78/javascript-get-url-parameters?id=123&type=post');

// "/post/78/javascript-get-url-parameters"
console.log(post_url.pathname);

Getting URL Query String & Parameters

The search property gives the query string / search parameters the url. The initial ? is included in it.

var post_url = new URL('https://usefulangle.com/post/78/javascript-get-url-parameters?id=123&type=post');

// "?id=123&type=post"
console.log(post_url.search);

Now to get the individual parameters in this query string, we will need to use the URLSearchParams object.

var post_url = new URL('https://usefulangle.com/post/78/javascript-get-url-parameters?id=123&type=post');

// new URLSearchParams from query string
var search_params = new URLSearchParams(post_url.search); 

// "id : 123"
// "type : post"
for(var i of search_params) {
	console.log(i[0] + ' : ' + i[1]);
}

The URLSearchParams object has several useful methods — get a single parameter value, changing a parameters's value, adding or deleting parameters. Check Getting URL Parameters with Javascript and Changing URL Parameters with Javascript to know more.

Getting URL Hash / Fragment

The url hash can be found with the hash property. The initial # is also included.

var post_url = new URL('https://usefulangle.com/post/78/javascript-get-url-parameters?id=123&type=post#container');

// "#container"
console.log(post_url.hash);