【问题标题】:Matching cookie string in Javascript with regex用正则表达式匹配 Javascript 中的 cookie 字符串
【发布时间】:2021-06-09 01:50:00
【问题描述】:

为了简单起见,我希望将 JavaScript 中的 cookie 与两个组进行匹配。这样我就可以按键、对顺序循环遍历结果。

我正在使用这个字符串进行测试:

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

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

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

【问题讨论】:

    标签: javascript regex typescript cookies


    【解决方案1】:

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

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

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

    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);
    });

    输出:

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

    【讨论】:

      【解决方案2】:
      /((?<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);
      }
        
      &lt;div id="result"&gt;&lt;/div&gt;

      【讨论】:

      • 浏览器不普遍支持命名捕获组。
      • 您可以在没有命名的捕获组的情况下执行此操作。但感谢您指出。不知道。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 2010-12-06
      • 2012-06-05
      • 2013-12-25
      • 1970-01-01
      相关资源
      最近更新 更多