From Query String to Cookie with JavaScript

One problem I’ve run into that I discussed in the post JavaScript Cookies – Baking Has Never Been So Easy! is that I am accustomed to always having access to my PHP super globals and functions. So when the idea of capturing a query string from an .html file was proposed I was at a loss.

Changing the whole site to PHP was not an option, and the server they were on wouldn’t allow for .htaccess modifications to make .html parse through the PHP engine or let us change the httpd.conf file.

JavaScript cookies were clearly the only way to save the query string, the trick was to get the data from the query string, specifically the value for code ie: index.html?code=from google rep

A regular expression came to the rescue:

var regex = new RegExp( "[\?&]code=([^&#]*)" );

It’s looking for an instance following these requirements (broken down to explain)

var regex = new RegExp( "[\?&]"         //Starting with ? or & (remember the ? needs to be escaped ie. \?
+"code"                                 // immediately followed by the strong 'code'
+"="                                    // immediately followed by the strong '='
+"([^&#]*)"                             // Collects unlimited ie. * characters until it hits the end, an & or a #
);

So we put together a function which we could pass the name from the query string that we want and then the function would return the value. After creating the regular expression we apply it to the window.location.href which is what JavaScript retrieves as the URL used to access that page.

function getQueryValue( name ) {
    var regex = new RegExp( "[\?&]"+name+"=([^&#]*)" );
    var results = regex.exec( window.location.href );
    if( results == null )
        return "";
    else
        return results[1];
}

If no match is found the function returns nothing. If something is found it returns the array value of the 1st callback group (ie. the first group surrounded by the ()) which in our case the value that we were looking for.

Now to use that function we would call the function, passing the name of the value we were looking for:

var value = getQueryValue('setting');

Then we could set the cookie from the variable value using the functions we created in JavaScript Cookies – Baking Has Never Been So Easy!

setCookie('setting',value,'','/');

What About Arrays?

What about the times that a value is passed in the query string as an array, such as: index.html?district[]=east&district[]=west

The regular expression above fails when introducing the [ and ] symbols into the query string and name of the value we are trying to retrieve through the function. That means that we are going to need to make some modifications, and escape the [ and ] symbols. We could do that outside the function, but it’s better practice to make a function that makes modifications like that within itself.

name = name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");

We use a regular expression looking for [ and ] and replace them with the escaped version \\[ and \\].

So even with that added as the first line of the function it still only returns the first value and not any additional values. What’s the point of passing a value as something[] if you can use it as an array with another something[]?

The only way I could find to get more than one result is using the match() function.

name = name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
var regex = new RegExp( "[\?&]"+name+"=([^&#]*)", 'gi' );
var matches = window.location.href.match(regex);

Match returns the array

array('district[]=east','&district[]=west');

The quickest way to separate out the values and put them in a new array is to split each member of the array on the = symbol and create the new array using just the first index of the split’s returned array.

var values = new Array();
for (var i=0; i < matches.length; i++) {
    var value = matches[i].split("=");
    values[i] = value[1];
}
return values;

Continue on to page 2: put all this together and learn to redirect without the query string with javascript

Pages: 1 2

This site runs on the Thesis WordPress Theme

Thesis Theme thumbnail

If you're someone who doesn't understand a lot of PHP, HTML, or CSS, Thesis will give you a ton of functionality without having to alter any code. For the advanced, Thesis has incredible customization possibilities via extensive hooks and filters. And with so many design options, you can use the template over and over and never have it look like the same site.

If you're more familiar with how websites work, you can use the fantastic Thesis User's Guide and world-class support forums to make more professional customizations than you ever thought possible. The theme is not only highly customizable, but it allows me to build sites with a much more targeted focus on monetization than ever before. You can find out more about Thesis below:

Leave a Comment

Previous post:

Next post: