Set jQuery Cookies With Value From Url Parameter

Setting a jQuery cookies is not that easy as native php cookies and getting url parameters in jQuery requires a bit of knowledge in regex. In this article we will explain how to get parameters from url with jQuery and set a cookie with it’s value.

Let’s supose we have the following url:

Set Jquery Cookies With Value From Url Parameter

Capture Url Parameter

Let’s start by capturing the url parameter.
We need to create a jQuery function that captures the url parameter. Let’s take a look at the function below.

function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(;
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));

This function returns a value based on the parameter name we want. If you want to get the ID value, just set a variable calling function getParameterByName.

var ID = getParameterByName('ID');

The ID variable will store ID value that we see on the url.

Next we are going to set a jQuery Cookie with this value. In order to set jQuery Cookies we need to include the latest jQuery library and jQuery Cookie plugin.

<script src="" type="text/javascript"></script>
<script src="js/jquery.cookie.js" type="text/javascript"></script>

Set the jQuery Cookies

Syntax for setting the cookie is preety easy.

if($.cookie('ID') == null || $.cookie('ID') == "") {
$.cookie('ID', ID);


First we check if cookie exists, if not, we create the cookie with value from ID variable.
Now if you want to check if the cookie is created properly go to Chrome->Developer Tools in Resources tab expand cookies and you can see the cookie we created under your domain.
That’s all for creating a jQuery Cookie with value from url parameter.


Leave a reply