Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
js dynamic regular expr

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.')
            }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

you can use just array method instead you don't need for regex for that, for example..

const values = cart_cookie.split(',');
values.foreach(value => { 
 if(value != product_id){
   values.push(`${product_id}:1`);
   setCookie('cart', values.join(','), 7);
 }
});
about 4 years ago · Juan Pablo Isaza Relatório

0

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! 🥳 But... I'm not quite sure what your product ids look like, but if they contain special characters (e.g. periods, question marks, etc.) it'll cause some issues with how your regex performs. I doubt you have things like question marks in it, but something like this illustrates my point:

let cart_cookie = '123.15:3,2.5.141:1';

/* ... */

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

I know, its a rather unlikely scenario -- and it might not even apply to you if you know your product ids won't contain anything tricky -- but if you're goal is to build an online shop, you'll probably want to cover all your bases. Even fixing that, this still has a potential issue, as this will only let you add a quantity of 1 to an item thats not already in the cart, with no ability to increment it after that. Not sure if thats what you're going for.

This veers off of the main question you posed, but a potentially better solution might be using the browser's localstorage (or sessionstorage) to keep track of the cart. This would allow you to use more familiar data structures to store this info, rather than a string that you have to pray you're parsing correctly. More info on that here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda