Slice a query string and store as object values using JavaScript

· 2 Comments · in JavaScript

I recently had a need to reuse query string values multiple times on a page.

Calling a function that parses the query string each time just isn’t efficient.

I decided to use a self-executing function I wrote that stores the values as properties of an object.

We’ve all been there, we need to get those query string values using JavaScript – then we think, I’ve done this before — but how did I do it. I know the code is around here somewhere…

I prefer to have values stored once to be accessible as needed.

This function:
- Self-executes
- Checks if a query string exists
- Extracts the fields and values from that string
- Decodes the values if they are URI encoded
- Creates a global object
- Checks to make sure the value used to name a property is alphanumeric
- Adds a property and value to the object for each field/value pair from the query string

I’m using an object name of QS. You can rename this to whatever suits your needs.

Example URI encoded query string

?client%3DJack%20Burton%20Clothing%20Inc.%26project%3DPork%20Chop%20Express%20Redesign

Non-encoded it would read:

?client=Jack Burton Clothing Inc.&project=Pork Chop Express Redesign

JavaScript
This is a self-executing function – meaning you do not have to call it. It will execute when the code is loaded.

(function(){
	//decode and remove first question mark
	var qStr = decodeURIComponent(location.search).replace(/\?/,"")
	
	//if query string empty
	if(qStr === ""){return false}

	//split to array
	qStr = qStr.split("&")

	//create global object
	QS = {}
	for(i=0;i<qStr.length;i++){
		var e = qStr[i].split("=")
		//property name - strip all but basic alphanumeric
		e[0] = e[0].toString()
			.toLowerCase()
			.replace(/[^a-zA-Z0-9]+/g,'')
		//property value - replace plus sign with blank space
		e[1] = e[1].replace(/\+/g,' ')
		//assign properties and values to object
		QS[e[0]] = e[1]
	}
})()

You can access the values in the following ways:

QS.client
QS.project
QS["client"]
QS["project"]

* In super-rare cases where a numeric value is used for a field name, ex. ?1=apple, you cannot access via dot notation, you will have to use QS["1"].

In action:

//JavaScript
document.getElementById("client").innerHTML=QS.client
//jQuery
$("#client").html(QS.client)

You can even take it a step further and add the function to an existing or new namespace. You can then access it via that namespace using dot notation.

For the following example we will create a namespace called “MYSITE”. To this namespace we will add a child object called “qs”. This child object will hold the result/values of our function.

The code is slightly different from above in that it does not create a global object named “QS”. Instead it adds the object “qs” to the “MYSITE” namespace and the function returns the result to the “qs” object.

JavaScript(namespaced)

if(typeof MYSITE==="undefined" || !MYSITE) MYSITE={};
MYSITE = {
	qs: (function(){
			//decode and remove first question mark
			var qStr = decodeURIComponent(location.search)
			    .replace(/\?/,"")
			//if query string empty
			if(qStr === ""){return false}
			//split to array
			qStr = qStr.split("&")
			//create global object
			var QS = {}
			for(i=0;i<qStr.length;i++){
				var e = qStr[i].split("=")
				//property name - strip all but basic alphanumeric
				e[0] = e[0].toString()
					.toLowerCase()
					.replace(/[^a-zA-Z0-9]+/g,'')
				//property value - replace plus sign with blank space
				e[1] = e[1].replace(/\+/g,' ')
				//assign properties and values to object
				QS[e[0]] = e[1]
			}
			//return object
			return QS
		})()
}

You can access the values in the following ways:

MYSITE.qs.client
MYSITE.qs.project
MYSITE.qs["client"]
MYSITE.qs["project"]

In action:

//JavaScript
document.getElementById("client").innerHTML=MYSITE.qs.client
//jQuery
$("#client").html(MYSITE.qs.client)

I hope you find this bit of reusable code helpful.

Great books are available on JavaScript and jQuery.

Tested in:
jQuery 1.7.2+
FF 3.6+, Safari, Chrome, IE8+, iOS

This entry was posted in JavaScript and tagged .
Bookmark the permalink.

2 Responses to Slice a query string and store as object values using JavaScript

  1. Hi there, You’ve done a fantastic job. I’ll certainly digg it and
    personally recommend to my friends. I’m confident they’ll be benefited from this site.

  2. FirstEthel says:

    I see you don’t monetize your site, don’t waste your traffic,
    you can earn extra cash every month because you’ve got hi quality content.
    If you want to know how to make extra $$$, search for:
    Boorfe’s tips best adsense alternative

Leave a Reply

Your email address will not be published. Required fields are marked *

*

To include code in your comment: Paste your code in the comment form, select it and then click the language link button below. This will wrap your code in a <pre> tag(or shortcode) and format it when submitted.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">