Javascript Querystring Parameters

Javascript Querystring Parameters

Javascript Querystring Parameters

Hi all, just wrote up a javascript object to parse url parameters. You can take parameters out of the querystring or the url hash.

Usage

//assuming 

url.href;
//returns 

url.path
//return /index/?foo=bar&baz=baa#test=true

url.get('foo');
//returns 'bar'

url.get('test');
//returns true

Script

var url = (function(){
	var _href = location.href;
	var _path = location.pathname;
	var _qs = location.search.replace(/\?/, '');
	var _hash = location.hash.replace(/\#/, '');
	
	var _parse = function(string){
		var params = string.split('&');
		var holder = [];
		
		for(var i = 0; i < params.length; i++){
				var temp 	= params[i].split('=');
				var key 	= temp[0];
				var val 		= temp[1];
				holder[key] = val;
		}
		return holder;
	};
	
	var _qs_params 	= _parse(_qs);
	var _hash_params = _parse(_hash);
	
	return {
		href:_href,
		path:_path,
		get:function(name){
			var retval = null;
			if(_qs_params[name] !== undefined){
				retval = _qs_params[name];
			} else if(_hash_params[name] !== undefined) {
				retval = _hash_params[name];
			}
			return retval;
		},
		go:function(loc){
			location.href = loc;
		},
		back:function(item){
			if(item !== undefined){
				item = -1;
			}
			history.go(item);
		}
	};
})();

About the Author

Rob McVey

I am a software developer/IT professional helping businesses save money through informed purchase consulting; website development and marketing; and process automation.