Home > Blockchain >  js dynamic regular expr
js dynamic regular expr

Time:11-30

hi I am coding an online shop , currently working on add to cart functionality, like to store product ids and their quantity in a cookie like this id1:qt1,id2:qt2... like to check if a product is already is in cart , looks like my regular expr doesn't work

            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('already in cart.')
            }

CodePudding user response:

Yep, your regex is off :)

It stumped me for a second, but its clear when you check what your "regex" string actually evaluates to: /product_id:d /. This is because the string you're passing in sees the \d as a literal d. To fix this, just throw another \ in there so the original \ is whats being escaped. Before, you were matching things like "apple:ddddddd".

Once you do that, your code DOES seem to work, but maybe just not like you expect it to? I've put your code into a function, since you would -- presumably -- be calling this every time you want to add an item to the cart, and added a console.log statement to show the end value of the "cookie."

// Just as a stand in 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('cart_cookie is now ', values.join(','));
        setCookie('cart', values.join(','), 7);
    }
    else {
        console.log('already in cart.')
    }
}


addCartItem('apples');
// already in cart.

addCartItem('kiwis');
// cart_cookie is now apples:2,oranges:3,bananas:1,kiwis:1

Its fixed!

  • Related