Get URL with JavaScript

At some point in time you need to get the current URL and do some logic based on it. JavaScript has handy API called window.location which has all the information related to the windows current location.

Running console.log(window.location); in the console or your JavaScript file will return the following Location object:

Location {
    origin: "", 
    host: "",
    hostname: "",
    href: "",
    origin: "",
    pathname: "/",
    port: "",
    protocol: "http:",
    search: ""
    assign: function,
    ancestorOrigins:    DOMStringList, 
    reload: function reload() { [native code] },
    replace: function () { [native code] },
    toString: function toString() { [native code] },
    valueOf: function valueOf() { [native code] }

Having a reference to the location you are now able to start tinkering away. Here a couple of examples.

Getting values from URL

var pathname = window.location.pathname;

Manipulating URL = 'super awesome values';

Redirecting URL

var newURL = "";
window.location = newURL;

One gotcha with the above snipper is make sure you add the protocol. e.g. http://.


In the event that you need to reload the current page you can also call window.location.reload.


Hopefully the above gives you enough of an insight into working with the current URL to get your out of trouble.