Path: csiph.com!weretis.net!feeder8.news.weretis.net!news.mb-net.net!open-news-network.org!.POSTED.178.197.213.187!not-for-mail From: Thomas 'PointedEars' Lahn Newsgroups: comp.lang.javascript Subject: Re: Create cookie from ID of tag Supersedes: <1931004.oMNUckLgyt@PointedEars.de> Date: Fri, 26 Mar 2021 17:33:41 +0100 Organization: PointedEars Software (PES) Lines: 81 Message-ID: <2578953.mvXUDI8C0e@PointedEars.de> References: <06c15260-54cb-43fd-99f0-cba71b0caa36n@googlegroups.com> <01863a61-d1bf-47ec-9955-1a1579e9aca2n@googlegroups.com> <48e39d8c-ec2d-4759-8ddd-8ac063e510c3n@googlegroups.com> Reply-To: Thomas 'PointedEars' Lahn Mime-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: 8Bit Injection-Info: gwaiyur.mb-net.net; posting-host="178.197.213.187"; logging-data="18425"; mail-complaints-to="abuse@open-news-network.org" User-Agent: KNode/4.14.10 Cancel-Key: sha1:XYGun2vGhGckSlowMSfBvEgY/ac= Cancel-Lock: sha1:xgg3I+5e1ZAgDOw2+2b3Up1ExJs= X-Face: %i>XG-yXR'\"2P/C_aO%~;2o~?g0pPKmbOw^=NT`tprDEf++D.m7"}HW6.#=U:?2GGctkL,f89@H46O$ASoW&?s}.k+&. Hi, this is the code I use to manage cookies: > > function createCookie(name,value,days) { > if (days) { > var date = new Date(); > date.setTime(date.getTime()+(days*24*60*60*1000)); As we know the number of (milli)seconds per standard day, … + days * 864e5 would be more efficient (if this way of moving a date value forward one day would be safe). > function readCookie(name) { > var nameEQ = name + "="; > var ca = document.cookie.split(';'); > for(var i=0;i < ca.length;i++) { [“for” is not a function. Do not write it as if it were.] for (var i = 0, len = ca.length; i < len; ++i) { > var c = ca[i]; > while (c.charAt(0)==' ') c = c.substring(1,c.length); Ouch. c = c.replace(/^ +/, ''); > if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); The argument c.length is superfluous. > } > return null; The return value on failure should be “undefined” instead because the function returns a primitive (String) value, not an object value, if successful. > } That is *very* inefficient and error-prone. Consider this: function readCookie (name) { return ( ( document.cookie.split(';') .map((cookie) => cookie.split('=')) .filter((cookie) => cookie[0] == name) || [] )[0] || [] )[1]; } [without .filter(), this is useful as an approach to obtain *all* cookies in an easily processible data structure], or function readCookie (name) { /* * NOTE: Cookie names typically do not contain * RegExp special characters; otherwise those * need to be escaped. */ return (document.cookie .match(new RegExp('(?:^|;)' + name + '=([^;]+)')) || [])[1]; } -- PointedEars FAQ: | | Twitter: @PointedEars2 | Please do not cc me./Bitte keine Kopien per E-Mail.