1

I am building an ecommerce application, part of which creates a cookie when the user adds products to a basket (US English: please read 'cart'). The application's logic often generates multiple baskets (and therefore multiple cookies) per user. Each cookie is given a key, which always begins with the string 'basket' following by an ascending integer. Each basket is given an id, which is a 32 character string, stored as the cookie's value.

Within the cookies, the user's basket ids are stored as strings, each with a name / value pair. I have managed to push all of the cookie name / value pairs into an array, such that the array reads:

["mcart=537244a1377f97374fff2233cdc29bdf", " mtoken=0f9a74b73d2f29b1c6088d63b7f4f4a5c545bbe9", " mexpires=1468626166000", " basket1=aw7j0r9ke3hq8tp20egf7105dozfn13i", " basket2=kpxpdnw6nnfyvawmk7n4s7pd9meaimy7", " basket3=9264k594wi9vgfiotkvz323n35yfvkkf"]

I have created a variable:

var name = 'basket';

My aim is to use javascript (presumably regex), or indeed jquery, to:

  • return the values for the key/value pairs with keys matching 'basket1', 'basket2' and 'basket3' (please note the extra space in the keys which directly follows the opening quotation marks);
  • continue to match and return values for future key/value pairs created (e.g. 'basket4', 'basket5', 'basket91');
    • return said values in an javascript array.

THANK YOU in advance to the community.

jonhendrix
  • 366
  • 2
  • 15
  • Can you give an example of what you expect the output to be for the above array? Is it an array like `["aw7j...", "kpxp...", ...]`? – user94559 Jul 15 '16 at 23:42
  • Possible duplicate of [How do I set/unset cookie with jQuery?](http://stackoverflow.com/questions/1458724/how-do-i-set-unset-cookie-with-jquery) – imtheman Jul 15 '16 at 23:44
  • Hi! Sure. I would like the array to be exactly as you have described. Thanks! – jonhendrix Jul 15 '16 at 23:47

1 Answers1

5
var cookies = ["mcart=537244a1377f97374fff2233cdc29bdf", " mtoken=0f9a74b73d2f29b1c6088d63b7f4f4a5c545bbe9", " mexpires=1468626166000", " basket1=aw7j0r9ke3hq8tp20egf7105dozfn13i", " basket2=kpxpdnw6nnfyvawmk7n4s7pd9meaimy7", " basket3=9264k594wi9vgfiotkvz323n35yfvkkf"];

var baskets = [];

for (var i = 0; i < cookies.length; i++) {
    var match = cookies[i].match(/basket\d+=(.*)/);
    if (match) {
        baskets.push(match[1]);
    }
}

console.log(baskets);

// Output:
// [ 'aw7j0r9ke3hq8tp20egf7105dozfn13i',
//   'kpxpdnw6nnfyvawmk7n4s7pd9meaimy7',
//   '9264k594wi9vgfiotkvz323n35yfvkkf' ]
user94559
  • 59,196
  • 6
  • 103
  • 103