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

https://mightytechno-283fdd.easywp.com/javascript/cooltricks.html?s=best

Access host name

window.location.hostname   //Result- mightytechno.com

Access protocol

window.location.protocol   //Result- https:

Access full URL

window.location.href   //Result- https://mightytechno-283fdd.easywp.com/javascript/cooltricks.html?s=best

Get path name of URL

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

Reload current URL

window.location.reload()

Assign different URL

This will load the new URL

window.location.assign("https://mightytechno-283fdd.easywp.com/javascript")

Replace with new URL

window.location.replace("https://mightytechno-283fdd.easywp.com/javascript")

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 http://example.com:8080

window.location.host //Result - example.com:8080
window.location.hosname //Result - example.com

Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124