js expressive dynamic pattern matching

Hey there! I'm in the process of coding an online store and am currently focusing on implementing the add to cart functionality. My goal is to save product IDs and their quantities in a cookie, which will look something like this: id1:qt1,id2:qt2... I've encountered an issue with my regular expression not working when trying to check if a product is already in the cart.

            const reg = new RegExp(`${product_id}:\d+`);
            if (!reg.test(cart_cookie)){
                const values = cart_cookie.split(',');
                values.push(`${product_id}:1`);
                setCookie('cart', values.join(','), 7);
            }
            else {
                console.log('This item is already in your cart.')
            }

Answer №1

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

Answer №2

Instead of using regex, you can simply utilize the array method to achieve the same result. Here's an example:

const items = cart_cookie.split(',');
items.forEach(item => { 
 if(item !== product_id){
   items.push(`${product_id}:1`);
   setCookie('cart', items.join(','), 7);
 }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method to dynamically navigate through JSON data and save an object at a specific level?

Here is an example json structure for a menu: { "menu": [{ "name": "vegetation", "id": "1", "children": [ { "name": "landuse", "id": "1.1", "children": [ ...

Can someone explain why my button icons are not aligning to the center properly?

I have a small issue with the icons I pulled from react-icons - they appear slightly raised within the buttons. How can I position them in the middle? That's my only query, but I can't post it alone due to mostly having code in my post. What an ...

Enforcing object keys in Typescript based on object values

I'm looking to design a structure where the keys of an object are based on values from other parts of the object. For example: type AreaChartData = { xAxis: string; yAxis: string; data: { [Key in AreaChartData['xAxis'] | AreaChart ...

Filtering a Two-Dimensional Array Using JavaScript

I am working with a basic 2D array that contains x, y coordinates as shown below: var c = [ [1,10], [2,11], [3,12], [4,13], [5,15] ]; I want to know how I can extract pairs from the array that meet specific conditi ...

I encountered an error in the console stating, "Uncaught ReferenceError: req is not defined," while trying to access req.query.id

Encountering the error 'Uncaught ReferenceError: req is not defined' when attempting to use req.query.id. Below is the content of my index.js file: const express = require("express"); const path = require("path"); const port = 8000; ...

What is the best way to select the enclosed <a> tag within an <li> element?

Below is the JavaScript code I have attempted: $('#footer').find('.browse li').click(function(e){ $(this).find('a').click(); }); Here is the relevant HTML: <div id="footer" class="span-24"><div ...

Modify the div class depending on the date

I am in the process of creating a simple webpage where I can keep track of all my pending assignments for college. Take a look at the code snippet below: <div class="assignment"> <div class="itemt green">DUE: 28/03/2014</div> </d ...

Retrieving AJAX content once it has finished loading

Apologies for my poor English. I have a function to handle ajax requests like this: $(document).on("click", ".ajax", function(e){ //dynamic content here, getting the href value from links. }); Now I need to manipulate the content of the ajax response AF ...

Vue.js SyntaxError: Identifier came out of nowhere

An error was reported by VUE debug mode in this line of my code: :style="{transform : 'translate3d(' + translateX + 'px,0, 0)'}"\ The documentation does not provide instructions on how to include a variable within a style binding ...

Establishing a default selection for a react dropdown menu filled with data retrieved from an API request

class Select extends React.PureComponent { constructor(props) { super(props) this.state = { value: this.props.initialValue } this.handleChange = this.handleChange.bind(this) } handleChange(e) { e.persist() ...

Access information from Google Sheets through an AJAX GET request

I am facing an issue with my code while trying to retrieve data from a Google spreadsheet that I have already published. I have set the share properties of the spreadsheet to 'anyone can edit' and provided the correct URL, but I am still encounte ...

Create an array in JavaScript using the JSON data that was returned

After receiving some JSON data from a REST call, I have successfully parsed and added totals to the data. The results can be viewed on the page (refer to this post: json sibling data). However, now I want to further break down the totals. Here is the initi ...

Unable to locate the specified script using node.js

Recently, I've started working with Javascript and Node.js. My current project is utilizing OpenMCT (https://github.com/nasa/openmct) and I'm facing an issue when trying to integrate a script as a plugin in an index.html file. Upon starting the N ...

Determining if the device is connected to the internet

Is there a way to create a unique code using HTML, JavaScript, or jQuery that executes a random action when the website detects that the device is offline? ...

Leveraging Ajax with Google Analytics

Currently, I am working on a website that utilizes Ajax calls to update the main content. In order to integrate Google Analytics tracking code using the async _gaq method, I need to push a _trackPageview event with the URI to _gaq. There are two approaches ...

301 redirection will be implemented on the upcoming static export

Working on a Next.js project, I utilized static export for better performance and SEO. Yet, I've come across an issue with URL changes. I'm looking to incorporate a 301 redirect to ensure search engines and users are directed to the correct pages ...

Encountered difficulty accessing the controller ActionResult from JavaScript代码

Resolution: After thorough investigation, I successfully identified and resolved the issue. Surprisingly, it was not related to the Javascript or Controller code as initially anticipated. The root cause stemmed from a .dll file that was causing discrepanci ...

Issue with loading glb file in three.js: The 'format' property is not compatible with this material

When loading a .glb file I created in Blender using three.js, I am encountering an error message three.module.js:7950 THREE.MeshStandardMaterial: 'format' is not a property of this material.. The rest of the content loads correctly. What does thi ...

Is it possible to declare variables within a React 'render' function?

I have data arranged in multiple columns on several rows, with a react element corresponding to each data element. The number of elements on the first row can vary between 4 and 6. For instance, I may display a user's name, birthday, and email. If t ...

Obtaining the initial value from an Observable in Angular 8+

Initially, I have a page form with preset values and buttons for navigating to the next or previous items. Upon initialization in ngOnInit, an observable provides me with a list of 3 items as the starting value - sometimes it may even contain 4 items. Ho ...