Approx 3 minutes read

Suppose you want to get the parameters of an URL like below in JavaScript

http://example.com?param1=value1&param2=value2

Below JavaScript code might come handy in this case

1
2
3
4
5
6
7
8
9
10
11
12
13
function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

var myvar = getUrlVars();

for (var key in myvar) {
	alert(key+" = " + myvar[key]);
}

It basically reads the current page url, perform some regular expression on the URL then saves the url parameters in an associative array, which we can easily access.