Get cookie by name
我有一个吸气剂来从cookie中获取价值。
现在,我有2个Cookie,名称分别为
我只想让这个吸气剂从义务cookie中获取值。
我该怎么做呢? 因此
1 2 3 4 5 6 7 8 9 10 11 | 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]); } } |
一种避免迭代数组的方法是:
1 2 3 4 5 | function getCookie(name) { var value =";" + document.cookie; var parts = value.split(";" + name +"="); if (parts.length == 2) return parts.pop().split(";").shift(); } |
演练
如果令牌中不存在令牌,则按令牌拆分字符串将生成一个具有一个字符串(相同值)的数组,或者如果在string中找到令牌,则将生成具有两个字符串的数组。
第一个(左)元素是令牌之前的字符串,第二个(右)元素是令牌之后的字符串。
(注意:如果字符串以令牌开头,则第一个元素为空字符串)
考虑到cookie的存储方式如下:
1 | "{name}={value}; {name}={value}; ..." |
为了检索特定的cookie值,我们只需要获取在"; {name} ="之后和下一个";"之前的字符串。在进行任何处理之前,我们在cookie字符串前添加";",以便每个cookie名称(包括第一个)都用";"和" ="括起来:
1 | "; {name}={value}; {name}={value}; ..." |
现在,我们可以先用"; {name} ="进行拆分,如果在cookie字符串中找到了令牌(即,我们有两个元素),我们将以第二个元素作为以cookie值开头的字符串结尾。然后,我们将其从数组(即pop)中取出,并重复相同的过程,但现在使用";"作为令牌,但这次拉出左侧字符串(即shift)以获取实际令牌值。
我希望在Cookie上使用单个正则表达式匹配项:
1 2 3 4 | window.getCookie = function(name) { var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)')); if (match) return match[2]; } |
或者我们也可以将其用作函数,请检查以下代码。
1 2 3 4 5 6 7 8 9 10 | 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---'); } } |
由于评论中的Scott Jungwirth而有所改进。
使用Cookie获取脚本:
1 2 3 4 5 6 7 8 9 10 | 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; } |
然后调用它:
1 | var value = readCookie('obligations'); |
我从quirksmode cookie页面上偷了上面的代码。您应该阅读它。
如果您使用jQuery,建议您使用此插件:
https://github.com/carhartl/jquery-cookie
https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js
1 2 | <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"> |
因此,您可以像这样读取Cookie:
1 | var value = $.cookie("obligations"); |
您也可以编写cookie:
1 2 | $.cookie('obligations', 'new_value'); $.cookie('obligations', 'new_value', { expires: 14, path: '/' }); |
删除Cookie:
1 | $.removeCookie('obligations'); |
其他一些使用正则表达式的答案中的方法并不涵盖所有情况,尤其是:
下面的方法处理这些情况:
1 2 3 4 5 | function getCookie(name) { function escape(s) { return s.replace(/([.*+?\^${}()|\[\]\/\\])/g, '\\$1'); }; var match = document.cookie.match(RegExp('(?:^|;\\s*)' + escape(name) + '=([^;]*)')); return match ? match[1] : null; } |
如果找不到该cookie,它将返回
笔记:
正则表达式注释:
4年后,ES6的方式更简单了。
1 2 3 4 5 6 7 8 | function getCookie(name) { let cookie = {}; document.cookie.split(';').forEach(function(el) { let [k,v] = el.split('='); cookie[k.trim()] = v; }) return cookie[name]; } |
我还创建了要点,以将其用作
这将读取所有cookie,而不是进行扫描。可以使用少量Cookie。
我已经修改了乔纳森(Jonathan)在此处提供的功能,通过使用正则表达式,您可以通过其名称获取cookie值,如下所示:
1 2 3 4 5 6 7 8 9 | function getCookie(name){ var pattern = RegExp(name +"=.[^;]*") matched = document.cookie.match(pattern) if(matched){ var cookie = matched[0].split('=') return cookie[1] } return false } |
如果返回空字符串,则表示该cookie存在但不具有值;如果返回false,则该cookie不存在。我希望这有帮助。
我知道这是一个老问题,但我也遇到了这个问题。仅作记录,开发人员mozilla网页中有一些API。
Yoy仅使用JS即可按名称获取任何cookie。该代码也更清晰,恕我直言(长行除外,我相信您可以轻松修复)。
1 2 3 4 | function getCookie(sKey) { if (!sKey) { return null; } return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g,"\\$&") +"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1")) || null; } |
如注释中所述,请注意,此方法假定键和值是使用encodeURIComponent()编码的。如果未对Cookie的键和值进行编码,则删除解码和encodeURIComponent()。
基里希给出了一个很好的解决方案。但是,当有两个具有相似名称的cookie值时,它将失败,这是针对这种情况的简单修复:
1 2 3 4 5 | function getCookie(name) { var value =";" + document.cookie; var parts = value.split(";" + name +"="); if (parts.length >= 2) return parts.pop().split(";").shift(); } |
您可以使用js-cookie库获取和设置JavaScript cookie。
包含到您的HTML中:
1 | <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"> |
要创建Cookie:
1 | Cookies.set('name', 'value'); |
读取Cookie:
1 | Cookies.get('name'); // => 'value' |
使用
这样,您可以轻松访问cookie
1 2 3 4 5 6 7 8 | Object.defineProperty(window,"Cookies", { get: function() { return document.cookie.split(';').reduce(function(cookies, cookie) { cookies[cookie.split("=")[0]] = unescape(cookie.split("=")[1]); return cookies }, {}); } }); |
从现在开始,您可以执行以下操作:
1 | alert( Cookies.obligations ); |
这也会自动更新,因此,如果您更改cookie,
总是效果很好:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function getCookie(cname) { var name = cname +"=", ca = document.cookie.split(';'), i, c, ca_length = ca.length; for (i = 0; i < ca_length; i += 1) { c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1); } if (c.indexOf(name) !== -1) { return c.substring(name.length, c.length); } } return""; } function setCookie(variable, value, expires_seconds) { var d = new Date(); d = new Date(d.getTime() + 1000 * expires_seconds); document.cookie = variable + '=' + value + '; expires=' + d.toGMTString() + ';'; } |
不需要jQuery或其他任何东西。纯旧的好JavaScript。
这是一个很简短的版本
1 2 3 4 | function getCookie(n) { let a = `; ${document.cookie}`.match(`;\\s*${n}=([^;]+)`); return a ? a[1] : ''; } |
请注意,我利用了ES6的模板字符串来组成正则表达式。
使用Cookie名称获取Cookie的简单功能:
1 2 3 4 5 6 7 8 9 10 11 | function getCookie(cn) { var name = cn+"="; var allCookie = decodeURIComponent(document.cookie).split(';'); var cval = []; for(var i=0; i < allCookie.length; i++) { if (allCookie[i].trim().indexOf(name) == 0) { cval = allCookie[i].trim().split("="); } } return (cval.length > 0) ? cval[1] :""; } |
显然,MDN从未听说过单词边界正则表达式字符类
1 2 3 4 5 6 | getCookie = function(name) { var r = document.cookie.match("\\b" + name +"=([^;]*)\\b"); return r ? r[1] : null; }; var obligations = getCookie('obligations'); |
在我看来,您可以将Cookie键值对拆分为一个数组,然后基于该数组进行搜索:
1 | var obligations = getCookieData("obligations"); |
运行以下命令:
1 2 3 4 5 6 7 8 9 10 | function getCookieData( name ) { var pairs = document.cookie.split(";"), count = pairs.length, parts; while ( count-- ) { parts = pairs[count].split("="); if ( parts[0] === name ) return parts[1]; } return false; } |
小提琴:http://jsfiddle.net/qFmPc/
甚至可能是以下情况:
1 2 3 4 5 6 7 | function getCookieData( name ) { var patrn = new RegExp("^" + name +"=(.*?);" ), patr2 = new RegExp("" + name +"=(.*?);" ); if ( match = (document.cookie.match(patrn) || document.cookie.match(patr2)) ) return match[1]; return false; } |
1 2 3 4 5 | function getCookie(name) { var pair = document.cookie.split('; ').find(x => x.startsWith(name+'=')); if (pair) return pair.split('=')[1] } |
在我的项目中,我使用以下功能按名称访问Cookie
1 2 3 4 5 6 | function getCookie(cookie) { return document.cookie.split(';').reduce(function(prev, c) { var arr = c.split('='); return (arr[0].trim() === cookie) ? arr[1] : prev; }, undefined); } |
获取Cookie的答案已经很不错了,但是这是我自己的解决方案:
1 2 3 4 5 6 7 8 9 | function getcookie(cookiename){ var cookiestring = document.cookie; var cookiearray = cookiestring.split(';'); for(var i =0 ; i < cookiearray.length ; ++i){ if(cookiearray[i].trim().match('^'+cookiename+'=')){ return cookiearray[i].replace(`${cookiename}=`,'').trim(); } } return null; } |
用法:
1 2 | getcookie('session_id'); // gets cookie with name session_id |
如果您只需要检查是否存在某些Cookie,则只需执行以下操作:
1 | document.cookie.split('logged=true').length == 2 |
如果cookie logging = true存在,那么您将得到2,如果不是1。
logging = true-将其更改为您的cookie name = value,或者只是一个名称
由javascript设定
1 | document.cookie = 'cookiename=tesing'; |
使用jquery-cookie插件通过jquery获取
1 2 3 | var value = $.cookie("cookiename"); alert(value); |
参考:https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
1 2 3 4 5 6 | document.cookie ="test1=Hello"; document.cookie ="test2=World"; var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/,"$1"); alert(cookieValue); |
我是这样做的。这样我就可以通过一个对象来访问各个值。这样,您就可以将Cookie传递给父对象,然后您就可以通过诸如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var cookies=getCookieVal(mycookie); alert(cookies.mykey); function getCookieVal(parent) { var cookievalue = $.cookie(parent).split('&'); var obj = {}; $.each(cookievalue, function (i, v) { var key = v.substr(0, v.indexOf("=")); var val = v.substr(v.indexOf("=") + 1, v.length); obj[key] = val; }); return obj; } |
我的解决方案是这样的:
1 2 3 4 5 6 | function getCookieValue(cookieName) { var ca = document.cookie.split('; '); return _.find(ca, function (cookie) { return cookie.indexOf(cookieName) === 0; }); } |
此函数使用Underscorejs _.find函数。如果cookie名称不存在,则返回undefined
查找现有cookie的功能方法。它返回一个数组,因此它支持多次出现相同的名称。它不支持部分键匹配,但是用正则表达式替换过滤器中的===很简单。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function getCookie(needle) { return document.cookie.split(';').map(function(cookiestring) { cs = cookiestring.trim().split('='); if(cs.length === 2) { return {'name' : cs[0], 'value' : cs[1]}; } else { return {'name' : '', 'value' : ''}; } }) .filter(function(cookieObject) { return (cookieObject.name === needle); }); } |
现在,当您以数组格式存储cookie时,就可以使cookie作为数组返回。
例如,您的cookie是array [35] =Khóa; array [36] = T ?; array [37] = C?a;
以及utf8的这段代码。
当您的Cookie名称内容[]且您存储的Cookie不在数组中时,一件事情就无法正常工作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | function getCookie(cname) { var ca = decodeURIComponent(document.cookie).split(';'); if (cname.indexOf('[]') > 0) { var returnVAlue = []; var nameArray = cname.replace("[]",""); for(var i = 0; i < ca.length; i++) { var c = ca[i]; // console.log(c); while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(nameArray) >= 0) { var valueString = c.substr(nameArray.length, c.length); var valueStringSlit = valueString.split('='); valueStringSlit[0] = valueStringSlit[0].substr(1,(valueStringSlit[0].length - 2)); // console.log(valueStringSlit); returnVAlue.push(valueStringSlit); } } } else { var returnVAlue = ''; var name = cname +"="; for(var i = 0; i < ca.length; i++) { var c = ca[i]; // console.log(c); while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { returnVAlue = c.substr(name.length, c.length); } } } if (returnVAlue != ''){ return returnVAlue; } return""; } // console.log(decodeURIComponent(document.cookie)); console.log(getCookie('array[]')); |
我喜欢使用闭包来获取名称的cookie值。下面的闭包将允许您按名称获取cookie值,但仅在cookie字符串已更新时才解析。
您可以使用以下方法检索Cookie的值:
1 | var foo = cookies.get("bar" ); |
码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | var cookies = ( function() { var cookieString = null; var cookieArray = []; function getValOf( name ) { if ( newCookies() ) { parseCookieString() } return cookieArray[ name ]; } // Check if new cookies have been added function newCookies() { return cookieString === document.cookie; } function parseCookieString() { cookieString = document.cookie; // Separate cookies var cookies = cookieString.split(";" ); // Empty previous cookies cookieArray = []; // Update cookieArray with new name-value pairs for ( var i in cookies ) { // Separate name and value var nameVal = cookies[ i ].split("=" ); var name = nameVal[ 0 ].trim(); var value = nameVal[ 1 ].trim(); // Add cookie name value pair to dictionary cookieArray[ name ] = value; } } return { /** * Returns value or undefined */ get: function( name ) { return getValOf( name ); } }; })(); |
以下函数将返回一对
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /** * Returns cookie key-value pair */ var getCookieByName = function(name) { var result = ['-1','-1']; if(name) { var cookieList = document.cookie.split(';'); result = $.grep(cookieList,function(cookie) { cookie = cookie.split('=')[0]; return cookie == name; }); } return result; }; |
Cookies示例:example
JS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | document.cookies = { create : function(key, value, time){ if (time) { var date = new Date(); date.setTime(date.getTime()+(time*24*60*60*1000)); var expires ="; expires="+date.toGMTString(); } else var expires =""; document.cookie = key+"="+value+expires+"; path=/"; }, erase : function(key){ this.create(key,"",-1); }, read : function(key){ var keyX = key +"="; 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(keyX) == 0) return c.substring(keyX.length,c.length); } return null; } } |
使用json或xml存储数组和对象
我会做这样的事情:
1 2 3 4 5 6 7 8 9 10 11 12 | function getCookie(cookie){ return cookie .trim() .split(';') .map(function(line){return line.split(',');}) .reduce(function(props,line) { var name = line[0].slice(0,line[0].search('=')); var value = line[0].slice(line[0].search('=')); props[name] = value; return props; },{}) } |
这将返回您的cookie作为对象。
然后您可以这样称呼它:
1 | getCookie(document.cookie)['shares'] |
Document.cookie Document属性cookie使您可以读写与文档关联的cookie。它充当Cookie实际值的获取器和设置器。
1 2 3 | var c = 'Yash' + '=' + 'Yash-777'; document.cookie = c; // Set the value:"Yash=Yash-777" document.cookie // Get the value:"Yash=Yash-777" |
来自Google GWT项目
获取所有cookie列表作为JSON对象的函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | var uriEncoding = false; function loadCookiesList() { var json = new Object(); if (typeof document === 'undefined') { return json; } var docCookie = document.cookie; if (docCookie && docCookie != '') { var crumbs = docCookie.split('; '); for (var i = crumbs.length - 1; i >= 0; --i) { var name, value; var eqIdx = crumbs[i].indexOf('='); if (eqIdx == -1) { name = crumbs[i]; value = ''; } else { name = crumbs[i].substring(0, eqIdx); value = crumbs[i].substring(eqIdx + 1); } if (uriEncoding) { try { name = decodeURIComponent(name); } catch (e) { // ignore error, keep undecoded name } try { value = decodeURIComponent(value); } catch (e) { // ignore error, keep undecoded value } } json[name] = value; } } return json; } |
设置和获取具有特定名称的Cookie。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | function getCookieValue(name) { var json = loadCookiesList(); return json[name]; } function setCookie(name, value, expires, domain, path, isSecure) { var c = name + '=' + value; if ( expires != null) { if (typeof expires === 'number') { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now var timeInMs = Date.now(); if (expires > timeInMs ) { console.log("Seting Cookie with provided expire time."); c += ';expires=' + (new Date(expires)).toGMTString(); } else if (expires < timeInMs) { console.log("Seting Cookie with Old expire time, which is in Expired State."); timeInMs = new Date(timeInMs + 1000 * expires); c += ';expires=' + (new Date(timeInMs)).toGMTString(); } } else if (expires instanceof window.Date) { c += ';expires=' + expires.toGMTString(); } } if (domain != null && typeof domain == 'string') c += ';domain=' + domain; if (path != null && typeof path == 'string') c += ';path=' + path; if (isSecure != null && typeof path == 'boolean') c += ';secure'; if (uriEncoding) { encodeURIComponent(String(name)) .replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent) .replace(/[\(\)]/g, escape); encodeURIComponent(String(value)) .replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent); } document.cookie = c; } function removeCookie(name) { document.cookie = name +"=;expires=Fri, 02-Jan-1970 00:00:00 GMT"; } function removeCookie(name, path) { document.cookie = name +"=;path=" + path +";expires=Fri, 02-Jan-1970 00:00:00 GMT"; } |
检查cookie名称是否有效:不能包含
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function isValidCookieName(name) { if (uriEncoding) { // check not necessary return true; } else if (name.includes("=") || name.includes(";") || name.includes(",") || name.startsWith("$") || spacesCheck(name) ) { return false; } else { return true; } } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test function spacesCheck(name) { var whitespace = new RegExp('.*\\s+.*'); var result = whitespace.test(name); console.log("Name:isContainSpace =", name,":", result); return result; } |
测试步骤以检查上述功能:
1 2 3 4 5 6 7 8 9 10 11 12 13 | setCookie("yash1","Yash-777"); setCookie("yash2","Yash-Date.now()", Date.now() + 1000 * 30); setCookie("yash3","Yash-Sec-Feature", 30); setCookie("yash4","Yash-Date", new Date('November 30, 2020 23:15:30')); getCookieValue("yash4"); // Yash-Date getCookieValue("unknownkey"); // undefined var t1 ="Yash", t2 ="Y ash", t3 ="Yash "; spacesCheck(t1); // False spacesCheck(t2); // True spacesCheck(t3); // True |
只是为了对此响应添加一个"官方"答案,我正在复制/粘贴该解决方案以从MDN设置和检索cookie(这是JSfiddle
1 2 3 4 5 6 7 8 | document.cookie ="test1=Hello"; document.cookie ="test2=World"; var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/,"$1"); function alertCookieValue() { alert(cookieValue); } |
在您的特定情况下,您将使用以下功能
1 2 3 | function getCookieValue() { return document.cookie.replace(/(?:(?:^|.*;\s*)obligations\s*\=\s*([^;]*).*$)|^.*$/,"$1"); } |
请注意,我仅将示例中的" test2"替换为"义务"。
1 2 3 4 | function GetCookieValue(name) { var found = document.cookie.split(';').filter(c => c.trim().split("=")[0] === name); return found.length > 0 ? found[0].split("=")[1] : null; } |