microtuts

Javascript: Get Variables From Querystring

I found this code somewhere I while ago. I left the authors credit at the top but I’m not sure where it came from.

/* Client-side access to querystring name=value pairs
	Version 1.2.3
	22 Jun 2005
	Adam Vandenberg
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = new Object()
	this.get=Querystring_get

	if (qs == null)
		qs=location.search.substring(1,location.search.length)

	if (qs.length == 0) return

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') // parse out name/value pairs separated via &

// split out each name=value pair
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0])

		if (pair.length == 2)
			value = unescape(pair[1])
		else
			value = name

		this.params[name] = value
	}
}

function Querystring_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
	if (default_ == null) default_ = null;

	var value=this.params[key]
	if (value==null) value=default_;

	return value
}

So throw that in your page, and then call that sucker like this:

// Parse the current page's querystring
var qs = new Querystring()

And then just go right on ahead and populate some variables with some query string variables:

var v1 = qs2.get("name1")
var v3 = qs2.get("name3", "default value")

Creating your first programming language is easier than you think.

Understanding how a programming language works is a surefire way to be a better developer. Read more.


Suggested Reading


written by Ryan Bosinger
Ryan is a web developer living and working in Banff Alberta. He also writes for giftsforpeoplewitheverything.com and freefoley.com.

Leave a Reply