0

I have a cookie on login to a webpage. HEre are the details of the cookie

"{"XXVCode":"T937848","PName":"Garneriere","PAddress":"Dublin 8, southgate","Participation":false,"Coding":true}" 

i need to capture XXVCode in a variable how could I do this in javascript on this webpage?

2 Answers2

1

Method 1:

You can use getCookie() function:

// Code collected from w3schools.com

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

Then you can call:

getCookie('XXVCode');

Method 2:

Note: your cookie string wrapped with double quote, it should be wrapped with single quote. Because double quote inside double quote will show syntax error.

var cookie = '{"XXVCode":"T937848","PName":"Garneriere","PAddress":"Dublin 8, southgate","Participation":false,"Coding":true}';

var cookieArray = JSON.parse(cookie)

const XXVCode = cookieArray['XXVCode'];
mahfuz
  • 2,728
  • 20
  • 18
0

convert to object, and then access key

const cookie = "{"XXVCode":"T937848","PName":"Garneriere","PAddress":"Dublin 8, southgate","Participation":false,"Coding":true}"

const cookieJSON = JSON.parse(cookie)

const XXVCode = cookieJSON['XXVCode']