简体   繁体   English

从多个Cookie读取值

[英]Reading values from multiple cookies

I have a js function readCookie which is currently reading value from 1 cookie named test1_cookie using regex. 我有一个js函数readCookie,当前正在使用正则表达式从名为test1_cookie的1个cookie中读取值。 However I want the same function to read test2_cookie as well. 但是我也希望使用相同的功能读取test2_cookie。 What's the best way to do that? 最好的方法是什么?

function readCookie(name) {
            var result = document.cookie.match(new RegExp('test1_cookie=([^;]+)'));
            result && (result = JSON.parse(result[1]));
            return result ? result[name] : null;
        }

I want to read test2_cookie as well. 我也想阅读test2_cookie。 || || does not work 不起作用

You could use the RegExp /(?:test[1-2])_cookie=([^;]+)/ which would create a non-capturing group for the test1/test2 match, and then match the subsequent cookie data. 您可以使用RegExp /(?:test[1-2])_cookie=([^;]+)/来为test1 / test2匹配创建一个非捕获组,然后匹配后续的cookie数据。

This one would work a little better as it would match any cookie's value in the format test_cookie (ie test1_cookie, test2_cookie, test3_cookie.) 这会更好一点,因为它将与任何cookie的值匹配,格式为test_cookie(即test1_cookie,test2_cookie,test3_cookie)。

/(?:test[0-9])\\_cookie\\=([^;]+)/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM