Look for partial name of cookie using Javascript -
on website use cookie show or hide content. depending on how users log in determine content visible them. i.e. if log in facebook, site looks cookie called "fbsr_3324". problem second part of cookie name changes every user (fbsr_2889 fbsr_9902 etc). therefore want know if can , suggest how can check first part of cookie name (i.e. existance of cookies starting fbsr_
here current current javascript use:
function checkcookie() { contentdiv=document.getelementbyid("cookiefb"); if (document.cookie.indexof("fbsr_")!=-1) { contentdiv.style.display="none"; } else { contentdiv.style.display="block"; } }
the code you're using perform if logged in using facebook, if had cookie set containing value 'fbsr_haha, gotcha'
perhaps job regex:
/^|;\s*fbsr_[0-9]{4}\=[^;]+;/.test(document.cookie);
should trick.
expression explanation:
^|;
: either start of string, or semi-colon\s*
: followed 0 or more spaccesfbsr_[0-9]{4}
: matches fsbr_ , sequence of 4 numbers\=
: write=
, need escape=
(lookarounds), best escape once not enough[^;]+
semi-colon at least once or more;
: literal semi-colon
where use expression:
function checkcookie() { contentdiv=document.getelementbyid("cookiefb"); if (/^|;\s*fbsr_[0-9]{4}\=[^;]+;/.test(document.cookie)) {//facebooker! contentdiv.style.display="none"; return;//return here, can leve else out } contentdiv.style.display="block"; }
well, should it.
however, can't myself, if ever more familiar js, , feel optimizing of scripts, consider this:
var checkcookie = (function(expr) { var contentdiv = document.getelementbyid('cookiefb'); return function() { contentdiv.style.display="block"; if (expr.test(document.cookie)) { contentdiv.style.display="none"; } }; }(/^|;\s*fbsr_[0-9]{4}\=[^;]+;/));
this optimized version of exact same code have. atm, code query dom element id cookiefb
every time called, , it'll create instance of regexp, too. using closure, can query dom once, , create instance of regexp once, , re-use each call.
it's bit more efficient, , micro-optimization in case, couldn't myself ;)
Comments
Post a Comment