使用正则表达式匹配 Javascript 中的 cookie 字符串

Matching cookie string in Javascript with regex

为简单起见,我希望将 JavaScript 中的 cookie 与两组匹配。这样我就可以按密钥对顺序遍历结果。

我正在测试这个字符串:

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

到目前为止,我已经想出了 /(\w+)=(\w+)/,但它在 Google 分析 cookie 中的周期失败了。

注意:Google 分析值是欺骗性的,保持相同的格式但不会导致安全问题。

您可以扫描到下一个 ; 或字符串结尾:

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

您可以使用拆分和正则表达式来选择键值对:

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, '');
  let val = item.replace(regex, '');
  console.log('key: ' + key + ', val: ' + val);
});

输出:

key: _ga_GZ83393, val: NOTGOOGLE.1.1613155331397.4.1.12345678.4
key: _ga, val: GA5.2.14144141.1135335686424
key: test, val: bob
/((?<index>\w+)=(?<value>[\w\.0-9]+))/g

感谢@Peter Thoeny 指出并非所有浏览器都支持命名组,所以这里是没有它的版本。

/((\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>