Indeed, there seems to be an issue with your regex pattern :)
It took me a moment to figure it out, but it becomes clear when you analyze what your "regex" string actually translates to: /product_id:d+/
. The problem lies in the fact that the backslash is not escaping the letter 'd' as intended, so it is treating '\d' literally instead of as a special character. This resulted in matches like "apple:ddddddd"
.
After correcting this issue by adding another backslash, the code appears to work, although perhaps not exactly as expected.
I've encapsulated your code into a function, assuming that you would call it each time you wish to add an item to the cart, and included a console.log
statement to display the final value of the "cookie."
// Just as a placeholder for actual values
let cart_cookie = 'apples:2,oranges:3,bananas:1';
function addCartItem(product_id) {
const reg = new RegExp(`${product_id}:\\d+`);
console.log(reg)
if (!reg.test(cart_cookie)){
const values = cart_cookie.split(',');
values.push(`${product_id}:1`);
console.log('Updated cart_cookie:', values.join(','));
setCookie('cart', values.join(','), 7);
}
else {
console.log('Item already in cart.')
}
}
addCartItem('apples');
// Item already in cart.
addCartItem('kiwis');
// Updated cart_cookie: apples:2,oranges:3,bananas:1,kiwis:1
The issue has been resolved! 🥳 However...
If your product ids contain special characters (such as periods or question marks), it may impact how your regex functions. While it's unlikely that you have such characters in your IDs, consider this example:
let cart_cookie = '123.15:3,2.5.141:1';
/* ... */
addCartItem('1.3.15');
// Item already in cart.
This scenario may be rare, and possibly irrelevant if you are certain that your product ids do not include tricky characters. But, if you are aiming to create an online store, covering all possibilities is essential.
Even after addressing that issue, there remains a potential limitation where only one quantity can be added to items not already in the cart, without the option to increment them further. It's worth considering whether this aligns with your intentions.
While this discussion deviates from your initial query, a better solution could involve utilizing the browser's local storage (or session storage) to manage the cart. This approach allows for the use of more conventional data structures to store information, rather than relying on parsing a string accurately.
For more details, refer to: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage