JS: Get URL (window.location)

By Xah Lee. Date: . Last updated: .

This page shows you how to get the URL using window.location.

The window.location object contains URL info. You can use it like this:

// sample output
// http://example.org/

The window.location object has the following properties. Their values are string.

window.location Properties
propertymeaningsample value
hrefentire URLhttp://www.weibo.com/2684694960/profile?topnav=1&wvr=5
hostthe host name and port number (if the URL has port number)www.example.com:8080
protocolprotocolhttp://, ftp://, file://
hostnamehost namewww.example.com
portport number8080
pathnamepathname, with beginning slash/js/js_get_url.html
hashthe part of url after #, including #.#hoot
searchpart of URL after ?, including ??topnav=1&wvr=5

If you set window.location.href the browser will load it.

You can open your Browser's JS Console and type window.location.href to see its value.

JS: Encode URL, Escape String

JS: Encode URL, Escape String


URL Topic

  1. JS: encodeURI
  2. JS: encodeURIComponent
  3. JS: escape
  4. JS: Get URL (window.location)
Like what you read? Buy JavaScript in Depth