When dealing with URLs in JavaScript, you will come across various syntax like location, window.location, or location.href, etc. Each piece of syntax has it use, and you will become a smarter developer by knowing the difference between them. In this article, I will show you how to correctly get the full URL with JavaScript.

If you go out and search for how to get the URL, you will come across a myriad of snippets and tips that may over-complicate this issue. In fact, you only need to know one word: location.

Solid Tip: Location is an object that holds all the information about the URL that you need.

One property in particular will hold the entire URL, which is a common value that people look for. This property is href. To correctly get the full URL is JavaScript, simply reference location.href. You can see a table of all available properties below. They are accessed as location.desiredproperty in your script.

The sample URL below is http://solidlystated.com/hardware/page/2/?cid=1

Properties Available in the Location Object

Property Type
hash “”
host “solidlystated.com”
hostname “solidlystated.com”
href “http://solidlystated.com/hardware/page/2/?cid=1”
pathname “/hardware/page/2/”
port “”
protocol “http:”
search “?cid=1”
assign assign()
reload() reload()
replace() replace()

Solid Tip: While location.href holds the current URL for reference, you can also set it to a new value and the page will immediately load the new URL.

What About ‘Window’ ?

What’s the difference between location and window.location? Nothing.

What’s the difference between location.href and window.location.href? Nothing again.

The location object references the top window by default, so it doesn’t matter.