Getting Query Parameter from URL in JavaScript

To most people’s surprise, there is not a standard way of accessing query string parameters from JavaScript without first having to parse the query string. Some frameworks and libraries have implemented ways of doing this, but it is not always the case. For example, the ever so popular jQuery has not implemented this, but rather lets you accomplish this with plugins.

There are a ton of ways of doing this, and you can find many very complicated approaches on Stack Overflow and where not. However, instead of giving you a very complicated solution that will work in many edge use cases, I will provide you with a very simple and easy to understand approach that works for most use cases. If you need something fancier, you can of course continue your search, but this will be sufficient in most cases.

So, enough words – let’s see some code!

function qs(name) {
    var query = window.location.search.substring(1); // Remove question mark
    var parameters = query.split('&');

    for (var i = 0; i < parameters.length; i++) {
        var pair = parameters[i].split('=');

        if (pair[0] == name) {
            return pair[1];
        }
    }

    return null;
}

The above function simply parses the query string by splitting it into an array by &. Then it simply loops through the query parameters and splits by = in order to isolate the parameter name and value, respectively. The result is that the parameter name is available at pair[0], and the value at pair[1], hence why we can easily check if the parameter name matches what we are looking for. If so, the value is returned, and otherwise NULL is returned.

To use the function, simply do as follows.

var id = qs('id');

Simple, right? Improvements are always welcome, but please remember that this is not intended to be a bullet-proof solution for every use case out there.

Be First to Comment

Leave a Reply

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