[英]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'). 我正在构建一个电子商务应用程序,当用户将产品添加到购物篮中时,其中一部分会创建一个cookie(美国英语:请阅读“购物车”)。 The application's logic often generates multiple baskets (and therefore multiple cookies) per user. 应用程序的逻辑通常会为每个用户生成多个篮子(因此会生成多个cookie)。 Each cookie is given a key, which always begins with the string 'basket' following by an ascending integer. 每个cookie都有一个键,该键始终以字符串“ basket”开头,后跟一个升序整数。 Each basket is given an id, which is a 32 character string, stored as the cookie's value. 每个购物篮都有一个ID(它是32个字符串),存储为cookie的值。
Within the cookies, the user's basket ids are stored as strings, each with a name / value pair. 在Cookie中,用户的购物篮ID以字符串形式存储,每个字符串都有一个名称/值对。 I have managed to push all of the cookie name / value pairs into an array, such that the array reads: 我已经设法将所有cookie名称/值对推入一个数组,以便该数组读取:
["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: 我的目标是使用javascript(大概是regex)或jquery来:
THANK YOU in advance to the community. 预先感谢社区。
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' ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.