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.

See also  Lightweight Mobile CSS Layout Library - flex.css

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('');

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:"

Getting the URL HostName

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

var post_url = new URL('');

// ""

Getting the URL Pathname

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

var post_url = new URL('');

// "/post/78/javascript-get-url-parameters"

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('');

// "?id=123&type=post"

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

var post_url = new URL('');

// new URLSearchParams from query string
var search_params = new URLSearchParams(; 

// "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.

See also  How to Convert Values to Numbers in Javascript

Getting URL Hash / Fragment

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

var post_url = new URL('');

// "#container"

Leave a Reply

Your email address will not be published. Required fields are marked *