Home > database >  Extract only cookie's value from a string
Extract only cookie's value from a string

Time:09-27

I have a cookie stored as a string in a variable. This cookie is received from the API server and will vary each time. But for ease lets say the string is:

var csrfCookie = "XSRF-TOKEN=eyJpdiI6ImtBWXVqS0RmRzN5Z241UUVibXc4M1E9PSIsInZhbHVlIjoiMDJZYWNtUk5MOUxPZzA4d1JVMU5Ldks0R2VoWUhjMGNDREpXT1FrQjVqeHhRQ0FRQWtKUW1sTFY3MlRCVlhKS3kwczlOM2FKSWNXL3pNS0RCa3lvc3cxb0p5TGlSeXdDcjRMOFh5bytHakJmcU45S0JuT2pxOXdxSlY1WXdpQnQiLCJtYWMiOiI0OTlkNjgyNWNlMTJmZGJiMWM0ZWNmYzJmNTE3NGM5OTc5MjA3ZWQ2ODg2MDIyYmM4N2FiNTljMDQzYzQxYzBkIn0=; expires=Sun, 26-Sep-2021 10:15:25 GMT; Max-Age=7200; path=/; domain=.somedomain.site"

The string contains all data that is unnecessary for me like cookie name XSRF-TOKEN= at the beginning and ; expires=Sun, 26-Sep-2021 10:15:25 GMT; Max-Age=7200; path=/; domain=.somedomain.site at the end.

I want to remove this data from this and get only the remaining string (i.e cookie value) as result and also url decode the remaining resultant value.

How do I do it?

CodePudding user response:

You should use regex expression to extract the value: const regex = /XSRF-TOKEN=(.*?);/;

var csrfCookie = "XSRF-TOKEN=eyJpdiI6ImtBWXVqS0RmRzN5Z241UUVibXc4M1E9PSIsInZhbHVlIjoiMDJZYWNtUk5MOUxPZzA4d1JVMU5Ldks0R2VoWUhjMGNDREpXT1FrQjVqeHhRQ0FRQWtKUW1sTFY3MlRCVlhKS3kwczlOM2FKSWNXL3pNS0RCa3lvc3cxb0p5TGlSeXdDcjRMOFh5bytHakJmcU45S0JuT2pxOXdxSlY1WXdpQnQiLCJtYWMiOiI0OTlkNjgyNWNlMTJmZGJiMWM0ZWNmYzJmNTE3NGM5OTc5MjA3ZWQ2ODg2MDIyYmM4N2FiNTljMDQzYzQxYzBkIn0=; expires=Sun, 26-Sep-2021 10:15:25 GMT; Max-Age=7200; path=/; domain=.somedomain.site";

const regex = /XSRF-TOKEN=(.*?);/;

var matches = regex.exec(csrfCookie);
console.log(matches[1]);

  • Related