From Query String to Cookie with JavaScript


Putting it All Together

It would be silly to have two entirely separate functions: one to deal with strings and one to deal with arrays, so I bundled it up into one easy function for y'all.

function getMixedQueryValue( name ) {
    if(name.indexOf('[]') > 0){
        name = name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
        var regex = new RegExp( "[\?&]"+name+"=([^&#]*)", 'gi' );
        var matches = window.location.href.match(regex);
        var values = new Array();
        for (var i=0; i < matches.length; i++) {
            var value = matches[i].split("=");
            values[i] = value[1];
        }
        return values;
    } else {
        var regex = new RegExp( "[\?&]"+name+"=([^&#]*)" );
        var results = regex.exec( window.location.href );
        if( results == null )
            return "";
        else
            return results[1];
    }
}

Which can be easily called like this then just set the cookies and you'll be on your way.

var setting = getMixedQueryValue('setting');
var districtsArr = getMixedQueryValue('district[]');

// URL:
// index.html?district[]=east&district[]=west&code=from google rep

Hide the Query String Once the Cookie is Set

One more special addition. Maybe you don't want your visitor to see the query string after they launch the page. Maybe you want your process to follow:

  1. Load page with query string
  2. Retrieve all values
  3. Set all values as cookies
  4. Redirect the page without appended query string

That's easy peasy, though I'm not gonna walk through it, you should catch the drift.

var setting = getMixedQueryValue('setting');
var districtsArr = getMixedQueryValue('district[]');
if(setting){
    setCookie('setting',setting,'','/');
}
if(districtsArr){
    setCookie('districts',districtsArr.join('|'),'','/');
}
if(getCookie('setting') && getCookie('districts')){
    window.location = window.location.href.split('?')[0];
}   

Magnificent!

Resources

Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


Similar Entries
Encoding & and HTML Entities in PHP
Special characters like MS Word's smart quotes can muck up a good custom piece to CMS work. First we're going to go over using a regular expression to make sure that & and any character code starting with & can always be save, and displayed in a form or webpage.
Open Links to a Different Site in a New Window with Prototype
Using the JavaScript library Prototype I can easily make any external links open in a new window, as well as change the rel="external" links to open in a target="_blank" window!
JavaScript Cookies - Baking Has Never Been So Easy!
Setting, updating retrieving and deleting cookies with JavaScript is a whole lot easier than I remembered. I've not got a quick library of functions available at my fingertips for such actions, wanna see?
Zip Code, Phone Number and Replacing Empty Fields with Really Easy Validation
While using the Really Easy Validation JavaScript validation library I've accumulated a few custom validations that for US phone numbers, US zip codes, Canadian postal codes as well as replacing empty fields or fields that don't contain a numeric value. Good stuff!
Block Content and Detect Wordpress Preview
Need to block tracking scripts in your WordPress Template when you preview your entries. I have just the way! Just a few lines into your functions.php file and header/footers and you can block Mint or Analytics in WordPress previews.
Next Post
US Census Data as a MySQL Database Playground
Previous Post
Birthday MySQL Query Hates Timestamps

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!