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:
- Load page with query string
- Retrieve all values
- Set all values as cookies
- 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
the newest discoveries, stories and shared tips!Come on, all the cool kids are doing it ;)


