Access URL and URL parts using Javascript

How to access URL and URL parts using JS

Accessing current URL or the part of the URL using vanilla javascript is pretty easy. You can use window object to do this.Lets use following URl for check who to extract each part of the URL

Access host name

window.location.hostname   //Result-

Access protocol

window.location.protocol   //Result- https:

Access full URL

window.location.href   //Result-

Get path name of URL

window.location.pathname   //Result- /javascript/cooltricks.html

Reload current URL


Assign different URL

This will load the new URL


Replace with new URL


Different between assign and replace

Assign and replace handle history in different way. If you use replace the previous URL will not be added to history and you can go back to that URL by clicking back button in browser. If you use assign it will keep previous URL in history and you can go back by browser back button.

Different between host and hostname

Hostname return the name of host only and host return name of the host with port number.

As a example if url is //Result -
window.location.hosname //Result -

Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124