Javascript Query Parser

Airshow 2 Tallied Votes 1K Views Share

INTRODUCTION
Have you ever wanted to pass data from one web page to another when server-side scripting is unavailable, and without setting a cookie? Ever wanted an efficient way to build url query strings? Well now you can.

SOLUTION
It is maybe little realised is that data can be successfully passed directly from page to page in a url's query string (the bit to the right of the ?, excluding the #name), as you might do for server-side interpretation, but in this case with client-side interpretation in Javascript. This is possible because Javascript makes the query string available as location.search , which can be parsed out very efficiently to discover any name|value pairs that appear in it.

The constructor QueryParser() allows each name|value pair from the query string to be made available as properties of a javascript object. This object also has methods to:

  • add further properties programmatically.
  • build a query string derived from the current object properties (with or without a base url prepended).
  • build a link, complete with query string derived from the current object properties (with or without a base url prepended).

These methods can be useful regardless of whether subsequent query string interpretation is client-side or server-side.

INSTALLATION
Save the code to a file, query_parser.js, then include it in the head of any page that needs to parse or build a query string, with:
<script src="/path/to/script/query_parser.js" type="text/javascript"></script>

By default, an instance of QueryParser(), $q, is created, containing properties representing each of current page's query string name|value pairs.

EXAMPLE
URL: http://www.mydomain.com/mydir/page.html?name=Smith&iq=8&shoe_size=110
$q.name will hold the value 'Smith'
$q.iq will hold the value '8'
$q.shoe_size will hold the value '110'

You are free to enquire $q's parameters as you would enquire "get" values server-side, and respond accordingly as per each page's particular needs, eg.:

if(parseInt($q.iq) < parseInt($q.shoe_size)) {
	alert( ['Oh no it\'s ' , $q.name , ' with his IQ of ' , $q.iq , ' and a shoe size of ' , $q.shoe_size].join('') );
}
else{
	alert( ['That\'s a relief, it\'s ' , $q.name , '. We need some brains around here.'].join('') );
}

CREATE YOUR OWN INSTANCE
Because QueryParser() is a contructor, you can create further instances of it to build query strings independent of $q, eg:

var $q2 = new QueryParser();

Now use $q2.set() (see below) to populate $q2 with as many properties as you need.

API
QueryParser()'s (and hence $q's) methods are as follows:

build(baseURL)
Description : Returns a string comprising the baseURL with all the $q properties appended as its query string.
Example : $q.build();//returns eg. ?name=Smith&iq=8&shoe_size=110
Example : $q.build('http://www.myDomain.com/page5.html');//returns eg. http://www.myDomain.com/page5.html?name=Smith&iq=8&shoe_size=110

buildLink(baseURL, linkTxt)
Description : Returns a string comprising a link with its href set to the baseURL with all the $q properties appended as its query string.
Example : $q.build('http://www.myDomain.com/page5.html');//returns eg. '<a href="http://www.myDomain.com/page5.html?name=Smith&iq=8&shoe_size=110">http://www.myDomain.com/page5.html?name=Smith&iq=8&shoe_size=110</a>'
Example : $q.build('http://www.myDomain.com/page5.html', 'click here');//returns eg. '<a href="http://www.myDomain.com/page5.html?name=Smith&iq=8&shoe_size=110">click here</a>'

clear(prop)
Description : Clears a property so that is will not appear in a subsequently built query string. Returns true if the property was cleared; false if the property does not exist.
Example : $q.clear('x');//clears $q.x
(This method is included for completeness and yes, you can also program $q.x = null ).

set(prop, value)
Description : Allows properties of $q to be set programmatically. Returns the value set.
Example : $q.set('x', 55); //sets $q.x to 55
(This method is included for completeness and yes, you can also program $q.x = 55 ).

SUMMARY
These methods can save a lot of nauseous string handling when building a URL with a query string.

So you now have a mechanism for:
a) passing data from page to page, with interpretation by client-side Javascript in a similar way to server-side languages, and without setting a cookie.
b) building URLs based on the query string that was passed to the current page.
c) building URLs with a query string based on any name|value pairs of your choosing.

Hope people find this useful.

Airshow

vmars commented: cool +2
pritaeas commented: Nicely written +6
function QueryParser(str) {
   /******************** QueryParser **********************
    ********************* by Airshow **********************
    *** http://www.daniweb.com/forums/member512379.html ***
    ********* Please keep this attribution intact *********/
	if (str) {
		str = unescape(str);
		if (str.indexOf("?") === 0) { str = str.substring(1); }
		var args = str.split("&");
		for (var i = 0; i < args.length; i++) {
			var pair = args[i].split("=");
			if (pair.length >= 1) {
				var prop = pair.shift();
				this[prop] = (pair.length == 1) ? pair[0] : (pair.length > 1) ? pair.join('=') : '';
			}
		}
	}
	this.set = function (prop, value) { return this[prop] = value; };
	this.clear = function (prop) {
		if(typeof this[prop] !== 'undefined') {
			this.set(prop, null);
			return true;
		}
		else { return false; }
	};
	this.build = function (baseURL, hashName) {
		baseURL = (!baseURL || typeof baseURL !== 'string') ? '?' : (baseURL.indexOf("?") === -1) ? (baseURL + '?') : baseURL;
		hashName = (!hashName || typeof hashName !== 'string') ? '' : (hashName.indexOf("#") === -1) ? ('#' + hashName) : hashName;
		var strArray = [];
		for (var prop in this) {
			if (typeof this[prop] !== 'undefined' && typeof this[prop] !== 'function' && this[prop] !== null) { strArray.push([prop, '=', this[prop]].join('')); }
		}
		return baseURL + strArray.join('&') + hashName;
	};
	this.buildLink = function (baseURL, linkTxt) {
		var url = this.build(baseURL);
		return [ '<a href="', url, '">', ((!linkTxt) ? url : linkTxt), '</a>' ].join('');
	};
}
var $q = new QueryParser(location.search);