I have worked with PHP extensively and it is very convenient to have all the URL parameters automatically assigned to the global array $_GET
. Here is an example:
http://www.example.org/?foo=bar
$_GET['foo']; // bar
I wish JavaScript had a similar API but we since it doesn't we can create it. We can create a GET variable where we can access each parameter the same way as in PHP. Let's get started.
In JavaScript, all the URL parameters are available under the window.location.search
property. For some reason, it includes the question mark. Don't ask me why.
The plan is to separate each variable into its own property in an object saving them as key value using regex:
var GET = (function(){
var get = {},
// the add function turns a key into an
// array if it is defined multiple times
add = function (key,value){
var cur = get[key];
if (cur.isArray){
get[key].push(value);
}else {
get[key] = [];
get[key].push(cur);
get[key].push(value);
}
},
search = document.location.search,
// decode special url characters like + into a (space)
decode = function (s) {
return decodeURIComponent(s.split("+").join(" "));
};
// The dreaded Regex
search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function (a,b,c) {
var key = decode(b),
value = decode(c);
if (get[key]){
add(decode(b),decode(c));
}else {
get[decode(b)] = decode(c);
}
});
return get;
})();
That's it! Now if you have a URL like this one: http://www.example.com/?foo=bar&p1=value
You can access the values like so:
GET.foo; // bar
GET.p1; // value
You can also test the for values before using them:
var email;
// email was not defined in the URL
if (GET.email) { // undefined
email = GET.email;
}else {
email = "No Email";
}
Also an added feature is, if a parameter is defined twice it is automatically converted into an array. http://www.example.org/?foo=bar1&foo=bar2
GET.foo; // ["bar1","bar2"]
There now you can easily access your URL parameters
Sign up for the Newsletter.
Comments
There are no comments added yet.
Let's hear your thoughts