Accessing querystring parameters on the client side
I hate mixing server side code into my javascript code. It's messy and it doesn't allow me to store my javscript in separate .js files.
I had to get access to certain querystring parameters from my client side code, so I decided to write a reusable javascript object to access the whole querystring collection.
//this is to store the key value pairs of the querystring
function qsObject(){
this.objects = new Array();
this.add = _add;
this.remove =_remove;
this.item = _item;
this.populateCollection =_populateCollection;
this.setRawString = _setRawString;
this.rawString ="";
this.setRawString();
this.populateCollection();
// to add items to the array
function _add(obj){
this.objects[this.objects.length] = obj;
}
//to remove items from the array
function _remove(index){
this.objects.splice(index, 1);
}
//gets a reference to an item object
function _item(searchKey){
searchKey = new String(searchKey);
searchKey = searchKey.toLowerCase();
for(i=0;i<this.objects.length;i++){
//the current key in the coll
var key = this.objects[i].key;
key = new String(key);
key = key.toLowerCase();
if(key == searchKey){
return this.objects[i];
}
}
}
function _setRawString(){
//Create regular expression object to retrieve the qs part
// Used regex 'cause the search property on the location object includes the bookmark stuff
var qsReg = new RegExp("[?][^#]*","i");
hRef = unescape( window.location.href);
var qsMatch = hRef.match(qsReg);
//removes the question mark from the url
qsMatch = new String(qsMatch);
qsMatch = qsMatch.substr(1, qsMatch.length -1);
this.rawString = qsMatch;
}
//takes a string and populates the array with the key/value pairs
function _populateCollection(rawString){
this.rawString = new String(this.rawString);
var rootArr = this.rawString.split("&");
for(i=0;i<rootArr.length;i++){
var tempArr = rootArr[i].split("=");
if(tempArr.length ==2){
tempArr[0] = unescape(tempArr[0]);
tempArr[1] = unescape(tempArr[1]);
this.add(new qsValue(tempArr[0], tempArr[1]));
}
}
}
function qsValue(key, value){
this.key = key;
this.value=value;
}
} //example of using the object
var qs= new qsObject();
var idObj= qs.item("id");
alert(idObj.key + " == " + idObj.value);