Jordan Schnur
Jordan Schnur

Reputation: 1353

Matching cookie string in Javascript with regex

For simplicity sake, I am looking to match a cookie in JavaScript with two groups. This is so I can loop through the results in a key, pair order.

I am testing with this string:

_ga_GZ83393=NOTGOOGLE.1.1613155331397.4.1.12345678.4; _ga=GA5.2.14144141.1135335686424; test=bob

So far I have come up with /(\w+)=(\w+)/ but it is failing with the periods that are in the Google analytic cookies.

NOTE: The Google Analytic values are spoofed, keeping the same format but as to not cause security issues.

Upvotes: 0

Views: 408

Answers (2)

DiegoRibeiro
DiegoRibeiro

Reputation: 91

/((?<index>\w+)=(?<value>[\w\.0-9]+))/g

Thanks to @Peter Thoeny to point out that the named groups are not supported in all browsers, so here is the version without it.

/((\w+)=([\w\.0-9]+))/g

https://regex101.com/r/lWpbgz/1

var cookie = "_ga_GZ83393=NOTGOOGLE.1.1613155331397.4.1.12345678.4; _ga=GA5.2.14144141.1135335686424; test=bob";
var match = null;
var regex = /((?<index>\w+)=(?<value>[\w\.0-9]+))/g;
var div = document.querySelector("#result");

match = regex.exec(cookie);
while(match != null) {
    div.innerText += match.groups.index + " = " + match.groups.value + "\n";
    console.log(match.groups.index + " = " + match.groups.value);
  match = regex.exec(cookie);
}
  
<div id="result"></div>

Upvotes: 1

Peter Thoeny
Peter Thoeny

Reputation: 7616

You can scan up to the next ; or end of string:

/(\w+)=([^;]*)/

You could use split and a regex to pick the key & value pairs:

const cookies = '_ga_GZ83393=NOTGOOGLE.1.1613155331397.4.1.12345678.4; _ga=GA5.2.14144141.1135335686424; test=bob';
const regex = /^ *([^=]*)=(.*)$/;
cookies.split(/;/).forEach(item => {
  let key = item.replace(regex, '$1');
  let val = item.replace(regex, '$2');
  console.log('key: ' + key + ', val: ' + val);
});

Output:

key: _ga_GZ83393, val: NOTGOOGLE.1.1613155331397.4.1.12345678.4
key: _ga, val: GA5.2.14144141.1135335686424
key: test, val: bob

Upvotes: 1

Related Questions