Javascript 按名称获取cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10730362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get cookie by name
提问by kirlich
I have a getter to get the value from a cookie.
我有一个 getter 从 cookie 中获取值。
Now I have 2 cookies by the name shares=
and by the name obligations=
.
现在我有 2 个 cookie 名称shares=
和名称obligations=
。
I want to make this getter only to get the values from the obligations cookie.
我想让这个 getter 只是为了从义务 cookie 中获取值。
How do I do this? So the for
splits the data into separate values and puts it in an array.
我该怎么做呢?因此,for
将数据拆分为单独的值并将其放入数组中。
function getCookie1() {
// What do I have to add here to look only in the "obligations=" cookie?
// Because now it searches all the cookies.
var elements = document.cookie.split('=');
var obligations= elements[1].split('%');
for (var i = 0; i < obligations.length - 1; i++) {
var tmp = obligations[i].split('$');
addProduct1(tmp[0], tmp[1], tmp[2], tmp[3]);
}
}
回答by kirlich
One approach, which avoids iterating over an array, would be:
一种避免迭代数组的方法是:
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
Walkthrough
演练
Splitting a string by token will produce either, an array with one string (same value), in case token does not exist in a string, or an array with two strings , in case token is found in a string .
如果字符串中不存在标记,则按标记拆分字符串将生成一个包含一个字符串(相同值)的数组,或者生成一个包含两个字符串的数组,以防在字符串中找到标记。
The first (left) element is string of what was before the token, and the second one (right) is what is string of what was after the token.
第一个(左)元素是标记之前的字符串,第二个(右)是标记之后的字符串。
(NOTE: in case string starts with a token, first element is an empty string)
(注意:如果字符串以标记开头,则第一个元素是空字符串)
Considering that cookies are stored as follows:
考虑到 cookie 的存储方式如下:
"{name}={value}; {name}={value}; ..."
in order to retrieve specific cookie value, we just need to get string that is after "; {name}=" and before next ";". Before we do any processing, we prepend the cookies string with "; ", so that every cookie name, including the first one, is enclosed with "; " and "=":
为了检索特定的 cookie 值,我们只需要获取“; {name}=" 之后和下一个“;”之前的字符串。在我们进行任何处理之前,我们在 cookie 字符串前面加上“;”,这样每个 cookie 名称,包括第一个,都用“;”和“=”括起来:
"; {name}={value}; {name}={value}; ..."
Now, we can first split by "; {name}=", and if token is found in a cookie string (i.e. we have two elements), we will end up with second element being a string that begins with our cookie value. Then we pull that out from an array (i.e. pop), and repeat the same process, but now with ";" as a token, but this time pulling out the left string (i.e. shift) to get the actual token value.
现在,我们可以先用 "; {name}=" 进行拆分,如果在 cookie 字符串中找到了 token(即我们有两个元素),我们最终会得到第二个元素是一个以我们的 cookie 值开头的字符串。然后我们从数组中取出它(即 pop),并重复相同的过程,但现在使用“;” 作为令牌,但这次拉出左边的字符串(即移位)以获得实际的令牌值。
回答by Jonathan Camenisch
I would prefer using a single regular expression match on the cookie:
我更喜欢在 cookie 上使用单个正则表达式匹配:
window.getCookie = function(name) {
var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
if (match) return match[2];
}
OR Also we are able to use as a function , check below code.
或者我们也可以用作函数,检查下面的代码。
function check_cookie_name(name)
{
var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
if (match) {
console.log(match[2]);
}
else{
console.log('--something went wrong---');
}
}
Improved thanks to Scott Jungwirth in the comments.
感谢 Scott Jungwirth 在评论中改进。
回答by mkoryak
use a cookie getting script:
使用 cookie 获取脚本:
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
then call it:
然后调用它:
var value = readCookie('obligations');
i stole the code above from quirksmode cookies page. you should read it.
我从 quirksmode cookie 页面窃取了上面的代码。你应该阅读它。
回答by trante
If you use jQuery I recommend you to use this plugin:
如果您使用 jQuery,我建议您使用此插件:
https://github.com/carhartl/jquery-cookie
https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js
https://github.com/carhartl/jquery-cookie
https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js
<script type="text/javascript"
src="//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js">
So you can read cookie like this:
所以你可以像这样读取cookie:
var value = $.cookie("obligations");
Also you can write cookie:
你也可以写cookie:
$.cookie('obligations', 'new_value');
$.cookie('obligations', 'new_value', { expires: 14, path: '/' });
Delete cookie:
删除cookie:
$.removeCookie('obligations');
回答by John S
The methods in some of the other answers that use a regular expression do not cover all cases, particularly:
使用正则表达式的其他一些答案中的方法并未涵盖所有情况,尤其是:
- When the cookie is the last cookie. In this case there will not be a semicolon after the cookie value.
- When another cookie name ends with the name being looked up. For example, you are looking for the cookie named "one", and there is a cookie named "done".
- When the cookie name includes characters that are not interpreted as themselves when used in a regular expression unless they are preceded by a backslash.
- 当 cookie 是最后一个 cookie 时。在这种情况下,cookie 值后不会有分号。
- 当另一个 cookie 名称以正在查找的名称结尾时。例如,您正在查找名为“one”的 cookie,并且有一个名为“done”的 cookie。
- 当 cookie 名称包含在正则表达式中使用时不被解释为自身的字符时,除非它们前面有反斜杠。
The following method handles these cases:
以下方法处理这些情况:
function getCookie(name) {
function escape(s) { return s.replace(/([.*+?\^${}()|\[\]\/\])/g, '\'); };
var match = document.cookie.match(RegExp('(?:^|;\s*)' + escape(name) + '=([^;]*)'));
return match ? match[1] : null;
}
This will return null
if the cookie is not found. It will return an empty string if the value of the cookie is empty.
null
如果未找到 cookie,这将返回。如果 cookie 的值为空,它将返回一个空字符串。
Notes:
笔记:
- This function assumes cookie names are case sensitive.
document.cookie
- When this appears on the right-hand side of an assignment, it represents a string containing a semicolon-separated list of cookies, which in turn arename=value
pairs. There appears to be a single space after each semicolon.String.prototype.match()
- Returnsnull
when no match is found. Returns an array when a match is found, and the element at index[1]
is the value of the first matching group.
- 此函数假定cookie 名称区分大小写。
document.cookie
- 当它出现在赋值的右侧时,它代表一个字符串,其中包含以分号分隔的 cookie 列表,而这些 cookie 又是name=value
成对的。每个分号后似乎有一个空格。String.prototype.match()
-null
找不到匹配项时返回。找到匹配项时返回一个数组,索引[1]
处的元素是第一个匹配组的值。
Regular Expression Notes:
正则表达式注意事项:
(?:xxxx)
- forms a non-matching group.^
- matches the start of the string.|
- separates alternative patterns for the group.;\\s*
- matches one semi-colon followed by zero or more whitespace characters.=
- matches one equal sign.(xxxx)
- forms a matching group.[^;]*
- matches zero or more characters other than a semi-colon. This means it will match characters up to, but not including, a semi-colon or to the end of the string.
(?:xxxx)
- 形成一个不匹配的组。^
- 匹配字符串的开头。|
- 分离组的替代模式。;\\s*
- 匹配一个分号后跟零个或多个空白字符。=
- 匹配一个等号。(xxxx)
- 形成匹配组。[^;]*
- 匹配零个或多个分号以外的字符。这意味着它将匹配最多但不包括分号或字符串末尾的字符。
回答by allenhwkim
4 years later, ES6 way simpler version.
4 年后,ES6 方式更简单的版本。
function getCookie(name) {
let cookie = {};
document.cookie.split(';').forEach(function(el) {
let [k,v] = el.split('=');
cookie[k.trim()] = v;
})
return cookie[name];
}
I have also created a gistto use it as a Cookie
object. e.g., Cookie.set(name,value)
and Cookie.get(name)
我还创建了一个要点以将其用作Cookie
对象。例如,Cookie.set(name,value)
和Cookie.get(name)
This read all cookies instead of scanning through. It's ok for small number of cookies.
这会读取所有 cookie 而不是扫描。少量的 cookie 没问题。
回答by Mohyaddin Alaoddin
I have modified the function that Jonathan provided here, by using regular expression you can get a cookie value by its name like this:
我修改了 Jonathan 在此处提供的函数,通过使用正则表达式,您可以通过其名称获取 cookie 值,如下所示:
function getCookie(name){
var pattern = RegExp(name + "=.[^;]*")
var matched = document.cookie.match(pattern)
if(matched){
var cookie = matched[0].split('=')
return cookie[1]
}
return false
}
If it returns empty string it means that the cookie exists but has no value, if it returns false then the cookie doesn't exist. I hope this helps.
如果它返回空字符串,则表示 cookie 存在但没有值,如果返回 false 则表示 cookie 不存在。我希望这有帮助。
回答by Martin Braun
Here is a one liner to get a cookie with a specific name without the need of any external lib:
这是一个单行代码,无需任何外部库即可获取具有特定名称的 cookie:
var cookie = ("; "+document.cookie).split("; YOUR_COOKIE_NAME=").pop().split(";").shift();
This answer is based on kirlich's brilliant solution. The only compromise of this solution is, that you will get an empty string when the cookie does not exist. In most cases this should not be a deal breaker, though.
这个答案基于kirlich 的出色解决方案。此解决方案的唯一妥协是,当 cookie 不存在时,您将得到一个空字符串。不过,在大多数情况下,这不应该是一个交易破坏者。
回答by Lanil Marasinghe
You can use js-cookielibrary to get and set JavaScript cookies.
您可以使用js-cookie库来获取和设置 JavaScript cookie。
Include to your HTML:
包含到您的 HTML 中:
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
To create a Cookie:
创建 Cookie:
Cookies.set('name', 'value');
To read a Cookie:
要读取 Cookie:
Cookies.get('name'); // => 'value'
回答by Marc
I know it is an old question but I came across this problem too. Just for the record, There is a little API in developers mozilla web page.
我知道这是一个老问题,但我也遇到了这个问题。只是为了记录,在开发者mozilla 网页中有一个小 API 。
Yoy can get any cookie by name using only JS. The code is also cleaner IMHO (except for the long line, that I'm sure you can easily fix).
Yoy 可以仅使用 JS 按名称获取任何 cookie。代码也更干净,恕我直言(除了长线,我相信你可以轻松修复)。
function getCookie(sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\$&") + "\s*\=\s*([^;]*).*$)|^.*$"), "")) || null;
}
As stated in the comments be aware that this method assumes that the key and value were encoded using encodeURIComponent(). Remove decode & encodeURIComponent() if the key and value of the cookie were not encoded.
如评论中所述,请注意此方法假定键和值是使用 encodeURIComponent() 编码的。如果 cookie 的键和值未编码,则删除 decode & encodeURIComponent()。