jonhendrix jonhendrix - 4 months ago 15
jQuery Question

Search array of string keys for matching variable and return all values using javascript / jquery

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.

Answer
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' ]