Slice a query string and store as object values using JavaScript

· 6 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.

6 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

  3. There is definately a lot to know about this issue. I like
    all of the points you have made.

  4. depoxito.com says:

    The best in class, Depoxito meet the expense of you high-end experience that refer the see
    and character of real VIP standarts, we pay for you the best fascinating to high-level experience of VIPs expect in any top stop casino, grand liven up casino royale provide you
    the other studio design element including the grand blackjack, offering our VIP Customer the best experience
    of a Salon privee table.
    New style table furthermore feature across the room in the manner of grand roulette
    upgraded on our provider playtechs mini prestige roulette
    which delivering more interesting and richer playing experience.
    The supplementary experience contains a sum of seven tables including five blackjack tables, one roulette table and
    one baccarat table. Grand living casino royale has been high hand-engineered to fit the needs of our customer to using
    it, and contains unique elements that is specially intended to maximize the
    impact value we got from our customers and diversify it to
    the existing network.
    Soon, Depoxito will build an greater than before authenticity
    technology on bring to life casino for our VIP member, these most advocate technology ever seen in rouse casino including this improved reality.
    Which allow players to experience products upon an entire additional level which is never
    seen in the past literally leaping out of the game and taking the blackjack, baccarat,
    roulette and additional game into the total entire level.

    Depoxito VIP Baccarat, we provide you the agreed exclusive stir VIP
    Baccarat that is played subsequent to going on to 7 players at the similar table and our deeply trained pretty enliven baccarat dealer.
    And of course our VIP member will quality as if they were
    in reality sitting at one of the summit casino baccarat
    table. This immersive gaming experience creates
    a hugely carefree way of being that our VIP players will find hard
    to surpass.
    Here is the list of liven up casino game that depoxito provide, we find
    the money for the widest range of conscious casino games on the
    publicize including : blackjack unlimited, blackjack prestige,
    roulette, baccarat, poker, hi-lo, sic bo, and grand stir casino royale such as Grand Baccarat, Grand
    Blackjack and Grand Roulette for our VIP member.
    And of course as a supporter of Depoxito you can enjoy every the games that we allow
    to you, all you habit to do is just visit our site http://www.depoxito.com and register it
    and no-one else takes stirring to 3 minutes and then youre
    good enough to exploit any game that you want.
    Be our VIP, living thing our VIP fanatic of course granted you the best assist
    you can acquire from us all you craving to be a VIP advocate is very easy.

    all you need is just save playing on our site, lump and undertaking following
    a VIP past the amount that our company had written, keep playing and
    our customer bolster will door you that you are promoted to become a VIP advocate on our site.

  5. Some individuals on the other hand pay a lot money at one time to boost the
    probability of winning. The system the place betting cash is
    through your financial institution is safe to work with, and the transaction is at all
    times between your account and the Ladbrokes.
    Easy system described in steps. Many are easy folks just struggling to
    get by. This information offers all the data that you must get into the sport.
    But the factor is that to increase your chances of winning, you want to put a guess each
    day. As an alternative, you’ll be able to get all the information you need
    from that very same site. As long because the proprietor of the Bitcoin looks after it correctly using a excessive-security
    wallet and two-issue authentication, it will be extremely troublesome for anybody else to get access
    to their funds. At any point, nonetheless, the bookie can soar in and make changes to the traces that are available to
    his players if knows he shall be getting heavy one sided action.

    In case you are one of those people who doesnt like cats, Im sorry to hear that.
    For the above example, it might seem like -7.5 (-110).
    Different players can legally buy Mega Thousands and thousands Lottery tickets online by
    way of the lottery agent you see mentioned above. For example, MEGA Tens of millions is a multi-state lottery and it operates in 11
    states. For instance, you would not need to choose simply any race horse
    in hopes of winning a wager. 5. Wager on sports activities by placing your wager.
    Once you click on on the sport of your choosing be sure to bookmark
    the web page so you’ll at all times have the most present and up to
    date sports betting odds at your disposal. In this method, you might choose a low quantity from the given set akin to 1-50 like 1.
    Some winning numbers have two consecutive numerals, although not on a regular basis.
    And then with the time you saved do something more productive than you’d
    have completed appearing like a poor individual.

  6. Ahmed says:

    Boys, I gotta boast. I found a hottie online who undressed for me.
    Just check my link.

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="">