How to GET parameters using javascript
1 min read

How to GET parameters using javascript

I was doing a sort of pagination system recently and I used the URL anchors to get the pages. Something like 'example.com/index.html#3' to go to page 3. Well, everything worked fine until I had to rewrite to system to use GET parameters, like in PHP. So my new url would have been 'example.com/index.html?page=3'. This makes sense in a way, since it's a rather common system and users are already used to seeing links like these.

In order to do this, I started from my old function:

function getAnchor() {
    var currentUrl = document.URL,
	urlParts   = currentUrl.split('#');
 
    return (urlParts.length > 1) ? urlParts[1] : null;
}

I created a new function, named urlGET, that took one parameter, named param. To make it work with the url I previously shown you, I would have called it like:

var page = urlGET('page');

Then, instead of splitting the URL once, based on the # character, I had to do it twice. First, I needed to split the url based on ?

function urlGET (param) {
    var params = document.URL.split('?');

};

So far, so good. If we have indeed parameters, then the params array should contain two items: the actual url (example.com/index.html) and the parameters (page=3). And since we can have more than one parameter (index.html?page=3&param2=test&param3=etc) a second splitting was required, this time based on the & character.

function urlGET (param) {
    var params = document.URL.split('?');

	if(params.length > 1) {
		params = params[1].split('&');
	}
};

This resulting array will now contain pieces like 'page=1', 'param2=test' and 'param3=etc'. A third split with = will get us a final array containing the parameter name in the first position and the parameter value in the second one. If the parameter name matches the one we want, we return the value. If nothing is found, we return null. Easy, as you can see for yourselves below:

function urlGET (param) {
    var params = document.URL.split('?');

	if(params.length > 1) {
		params = params[1].split('&');
				
		for (var  i = 0, len = params.length; i < len; i++) {
			if (params[i].split('=')[0] === param) {
				return params[i].split('=')[1];
			}
		}
	}

	return null;
};