How to find out if there is a cookie?

So, I am making a simple JS function like

function writeCookie() { var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height; document.cookie=the_cookie } 

how tm make sure users_resolution is set?

+4
source share
4 answers

You can write a function like this:

  function getCookie(cName) { var cVal = document.cookie.match('(?:^|;) ?' + cName + '=([^;]*)(?:;|$)'); if (!cVal) { return ""; } else { return cVal[1]; } } 

Then, after you set the cookie, you can call getCookie() and check its return value, if it is an empty string, or "" which is false , then the cookie does not exist, otherwise you have a valid value cookie

The above paragraph in code:

 var cookie = getCookie("users_resolution"); if (!cookie) { // cookie doesn't exist } else { // cookie exists } 
+4
source

If you just do

 var cookies = document.cookie; 

then the cookies line will contain a list of pairs of cookie name values ​​separated by a semicolon. You can split the string into ";" and view the results by checking the availability of your cookie name.

+3
source

I know that you did not mark this as jQuery, but I created a jQuery plugin for processing cookies , and this is a snippet that reads the cookie value:

  /** * RegExp Breakdown: * search from the beginning or last semicolon: (^|;) * skip variable number of spaces (escape backslash in string): \\s* * find the name of the cookie: name * skip spaces around equals sign: \\s*=\\s* * select all non-semicolon characters: ([^;]*) * select next semicolon or end of string: (;|$) */ var regex = new RegExp( '(^|;)\\s*'+name+'\\s*=\\s*([^;]*)(;|$)' ); var m = document.cookie.match( regex ); // if there was a match, match[2] is the value // otherwise the cookie is null ?undefined? val = m ? m[2] : null; 
+1
source

You might want to use indexOf to check if it exists:

 if(document.cookie.indexOf('users_resolution=') > 0){ // cookie was set } 
0
source

All Articles