2

I using jquery cookie plugin and here are my codes:

$('.Bookmark').click(function () {
    var id = $(this).attr('rel');
    if ($(this).hasClass('RedHeart')) {
        $(this).removeClass('RedHeart');
        $.removeCookie('Bookmarkid_' + id, id);
        $(this).attr('title', 'Add');
    } else {
        $(this).addClass('RedHeart');
        $.cookie('Bookmarkid_' + id, id, { expires: 3650 });
        $(this).attr('title', 'remove');
    }
});

$('.Bookmark').each(function () {
    var id = $(this).attr('rel');
    var $this = $(this);
    if ($.cookie('Bookmarkid_' + id) == id) {
        $this.addClass('RedHeart');
        $this.attr('title', 'remove');
    }
});

I'm wondering how can I find all cookies that set with a similar name. for example I set set 3 cookies with these names:

Bookmarkid_3132509
Bookmarkid_3432502
Bookmarkid_4433342

now I want to find and return all cookies that start with Bookmarkid_ name. I need something like this:

if ($.cookie().indexOf("Bookmarkid_") === 0) {
    alert('yes')
}

Edit: it's not duplicate and not related to that topic, Still not solved my problem!!!

Pedram
  • 15,766
  • 10
  • 44
  • 73
  • @Satpal I tried it before, not solved my problem! I think it's not related to my question at all, but you marked it as duplicated! my problem not solved yet. – Pedram May 30 '16 at 06:03
  • 1
    I have reopened it, Try `if(Object.keys($.cookie()).some(function(k){ return ~k.indexOf("Bookmarkid_") })){ // it has Bookmarkid_property }` – Satpal May 30 '16 at 06:05

1 Answers1

4

Read all available cookies: $.cookie(); // => { "name": "value" }

So

Object.keys($.cookie()).forEach(function(cookieName) {
  if (cookieName.indexOf("Bookmarkid_") === 0) {
    alert('yes')
  }
});

// next one return you only filtered cookies
Object.keys($.cookie()).reduce(function(collector, cookieName) {
  if (cookieName.indexOf("Bookmarkid_") === 0) {
    collector[cookieName] = $.cookie(cookieName);
  }
  return collector;
}, {});

// to filter cookies Names
 Object.keys($.cookie()).filter(function(cookieName) {
   return cookieName.indexOf('Bookmarkid_') === 0;
});
Vasiliy vvscode Vanchuk
  • 7,007
  • 2
  • 21
  • 44
  • Thanks, and just an extra question, how can I return these cookies with full name? I mean return `Bookmarkid_3132509` `Bookmarkid_3432502` `Bookmarkid_4433342` for example in an array. – Pedram May 30 '16 at 06:10
  • Thanks for your help & answer – Pedram May 30 '16 at 06:14