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.

Want to become a better web developer?

Join over 25,000 other developer & designers who get awesome links to the best news and articles each week delivered directly to their inbox.

1 Comment

  1. window.location.href
    > “http://localhost:2111/#somethingSomething”
    > “http://localhost:2111”

This post currently has one response. What do you think?

You can use basic HTML when posting code, please turn all < characters into &lt; or > into &gt;
If the code is multi-line, use <pre><code></code></pre>

Leave a Reply

Your email address will not be published. Required fields are marked *