Reputation: 5155
I'm reading through a bunch of random "Header" information in node.
It looks something like this:
_Aa:GA1.1.78037747.867108, 44907=5xyz; Webstorm-a36041d5=9fbb-48e9-b19e-e3f0a3282151; srce=coolernode; nsid=1234; cookie_data=T%3D1; _gat_PP=1;
Problem: I'm trying to write a regEx or something to parse out "cookie_data" value from the string.
Is it possible to convert it to a map or extract cookie_data=T%3D1?
I've tried doing:
const i= str.indexOf('cookie_data');
const res = str.chatAt(i);
But still going nowhere, since I can't keep traversing until i get ';'
Wondering to see if there's any other effective way to extract info?
Upvotes: 2
Views: 47
Reputation: 40434
You can use cookie package to parse the cookie and you will get all the other values too, not only cookie_data
const cookie = require('cookie');
const string = '_Aa:GA1.1.78037747.867108, 44907=5xyz; Webstorm-a36041d5=9fbb-48e9-b19e-e3f0a3282151; srce=coolernode; nsid=1234; cookie_data=T%3D1; _gat_PP=1$
const parsed = cookie.parse(string);
console.log(parsed.cookie_data); // T=1 (decoded)
/*
{ '_Aa:GA1.1.78037747.867108, 44907': '5xyz',
'Webstorm-a36041d5': '9fbb-48e9-b19e-e3f0a3282151',
srce: 'coolernode',
nsid: '1234',
cookie_data: 'T=1',
_gat_PP: '1' }
*/
or since you were trying a regex, use match
with a capture group to get the value of cookie_data
, and decodeURIComponent
to decode the value and get T=1
instead of T%3D1
const string = '_Aa:GA1.1.78037747.867108, 44907=5xyz; Webstorm-a36041d5=9fbb-48e9-b19e-e3f0a3282151; srce=coolernode; nsid=1234; cookie_data=T%3D1; _gat_PP=1;'
const [,data] = string.match(/cookie_data=(.+?);/);
console.log(data, decodeURIComponent(data));
Upvotes: 1
Reputation: 370999
Use match
to match the text found between two parts of a string:
const str = '_Aa:GA1.1.78037747.867108, 44907=5xyz; Webstorm-a36041d5=9fbb-48e9-b19e-e3f0a3282151; srce=coolernode; nsid=1234; cookie_data=T%3D1; _gat_PP=1;'
const found = str.match(/cookie_data=([^;]+);/)[1];
console.log(found);
Or you can split by semicolons and make an object representing the string, and access the appropriate property:
const str = '_Aa:GA1.1.78037747.867108, 44907=5xyz; Webstorm-a36041d5=9fbb-48e9-b19e-e3f0a3282151; srce=coolernode; nsid=1234; cookie_data=T%3D1; _gat_PP=1;'
const splits = str.split('; ');
const obj = splits.reduce((obj, substr) => {
if (!substr.includes('=')) return obj;
const [key, value] = substr.split('=');
obj[key] = value;
return obj;
}, {});
console.log(obj);
console.log(obj.cookie_data);
Upvotes: 3