GET Request Parameter with JavaScript

I found an easy method to get url parameters with JavaScript. The beauty is that it uses a JavaScript closure to cache the values so that it can be called multiple times without unneeded processing:

var urlParameter = (function() {
    var parameters = undefined;
    return function (paramName) {
        if (parameters == undefined) {
            parameters = {};
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                parameters[hash[0]] = hash[1];
            }
        }
        return parameters[paramName];
    }
}());

Usage:

urlParameter(parameterName);
Advertisement

,

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.