开发者

Javascript Cookies get by regex name

Hi how can i get cookies by regex names assuming开发者_如何学C that i have this cookies in browser cache

name:  value:
text1  something
test   something
text2  something
4      bla

like get cookies regex ('test'+onlynumbers)

returns

text1  something
text2  something


Something like this should work (untested):

var getCookieByMatch = function(regex) {
  var cs=document.cookie.split(/;\s*/), ret=[], i;
  for (i=0; i<cs.length; i++) {
    if (cs[i].match(regex)) {
      ret.push(cs[i]);
    }
  }
  return ret;
};
getCookieByMatch(/^text\d+=/); // => ["text1=x;...", "text2=y..."]


Well, this is a way but not an elegant one I guess:

// demo cookie data
document.cookie="text2=mu";
document.cookie="text1=mu2";
document.cookie="otherText=mu3";

// helper function from 
// http://codecandies.de/2010/02/15/js-library-namespace-und-erste-funktionen/
function getCookie(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;
}

// the function in question
function getCookieArray(regexp) {
    cookieString = document.cookie;
    filterResult = cookieString.match(regexp);
    returnArr = {};
    for(var i=0; i < filterResult.length; i++) {
      returnArr[filterResult[i]]=getCookie(filterResult[i]);
    }
    return returnArr;
}

//demo run
function run() {
   filteredCookies = getCookieArray(/text[0-9]+/g);
   for(var key in filteredCookies)
      alert(key+":"+filteredCookies[key]);
}

run();

Note that you need to add a "g" at the end of the regexp to get all cookies matching and not just the first one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜