Nathan Brown
Nathan Brown

Reputation: 257

Storing Spaces and Colons in Cookie JavaScript

I am making a webpage with a form that saves the data you type in cookies in case you accidentally close the tab or navigate away before submitting.

I would like to know if there is a way to allow whitespace and colons to be in my cookie's data? For instance if user types "test test", on refresh the cookie will be stored and displayed as "test%2520test". Similarly colons display as "%3A". I believe this is possible with using encodeURIComponent but I am not sure exactly how. Below I will include my saveVideo, setCookie, and readCookie JS functions as well as an example input field.

Also, bonus question: What would be the best way to delete each cookie's data upon submit of the form?

<input id="video" name="video" type="text" onchange="saveVideo(this.value);"/>

function saveVideo(cookieValue)
        {
            var sel = document.getElementById('video');

            saveclass = saveclass ? saveclass : document.body.className;
            document.body.className = saveclass + ' ' + sel.value;

            setCookie('video', cookieValue, 1   );
        }   


function setCookie(cookieName, cookieValue, nDays) {
            var today = new Date();
            var expire = new Date();

            if (nDays==null || nDays==0)
                nDays=1;

            expire.setTime(today.getTime() + 60 * 60 * 1000);
            document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
        }


function readCookie(name) {
          var nameEQ = name + "=";
          var ca = document.cookie.split(';');
          for(var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
          }
          return null;
        }

        </script>

Any tips, pointers, general help is much appreciated!

Upvotes: 0

Views: 1362

Answers (1)

gaganshera
gaganshera

Reputation: 2639

Just change your code to following in the readCookie function, using decodeURIComponent:

return decodeURIComponent(c.substring(nameEQ.length, c.length));

Upvotes: 1

Related Questions