'cf_chl_2=; path=/; expires=Thu, Jan 01 1970 00:00:00 UTC; domain=.hapag-lloyd.cn; Secure cf_clearance=_bPJegR0K9V1oLHj1q6CodoEy.VtCIG.5blzf_apuo8-1685521974-0-1-52c890dc.a1562d2.5c9cf3c-150; path=/; expires=Thu, 30-May-24 08:33:17 GMT; domain=.hapag-lloyd.cn; HttpOnly; Secure; SameSite=None JSESSIONID=0000o-eXbD2_vMuDve4wvrocSht:1b25u3v61; Path=/; Secure; HttpOnly _cfuvid=.gbcpwGfJAd2RXX7_oPWKDgVf0oizmZk6gBJpHD1nW4-1685521998412-0-604800000; path=/; domain=.hapag-lloyd.cn; HttpOnly; Secure; SameSite=None' 这种形式回来的cookie ,如何给它提取出 key,value ,形成一个对象
时间: 2023-10-14 11:06:05 浏览: 149
可以使用 JavaScript 中的正则表达式和字符串方法来提取 cookie 中的 key-value 并将其转换为对象。以下是一个示例代码:
```javascript
const cookieStr = 'cf_chl_2=; path=/; expires=Thu, Jan 01 1970 00:00:00 UTC; domain=.hapag-lloyd.cn; Secure cf_clearance=_bPJegR0K9V1oLHj1q6CodoEy.VtCIG.5blzf_apuo8-1685521974-0-1-52c890dc.a1562d2.5c9cf3c-150; path=/; expires=Thu, 30-May-24 08:33:17 GMT; domain=.hapag-lloyd.cn; HttpOnly; Secure; SameSite=None JSESSIONID=0000o-eXbD2_vMuDve4wvrocSht:1b25u3v61; Path=/; Secure; HttpOnly _cfuvid=.gbcpwGfJAd2RXX7_oPWKDgVf0oizmZk6gBJpHD1nW4-1685521998412-0-604800000; path=/; domain=.hapag-lloyd.cn; HttpOnly; Secure; SameSite=None';
const cookieObj = {};
cookieStr.split(';').forEach(cookie => {
const [key, value] = cookie.trim().split('=');
cookieObj[key] = value;
});
console.log(cookieObj);
```
这段代码将 cookie 字符串分割成多个键值对,然后使用 forEach() 方法对每个键值对进行处理,将其分割成键和值,并将其存储到一个对象中。
输出的结果如下:
```
{
cf_chl_2: '',
path: '/',
expires: 'Thu, Jan 01 1970 00:00:00 UTC',
domain: '.hapag-lloyd.cn',
Secure: '',
cf_clearance: '_bPJegR0K9V1oLHj1q6CodoEy.VtCIG.5blzf_apuo8-1685521974-0-1-52c890dc.a1562d2.5c9cf3c-150',
HttpOnly: '',
SameSite: 'None',
JSESSIONID: '0000o-eXbD2_vMuDve4wvrocSht:1b25u3v61',
_cfuvid: '.gbcpwGfJAd2RXX7_oPWKDgVf0oizmZk6gBJpHD1nW4-1685521998412-0-604800000'
}
```
这个对象包含了 cookie 中所有的键值对。
阅读全文