javascriptcookiesgoogle-analyticscookieconsent

How to delete a cookie if I only know its name's first few characters - with Javascript?


I am creating my own Cookie Consent, and I've experienced a problem with revoking consent - so the user has already allowed consent, but changed their mind and wants to deny them.

When it comes to Google Analytics cookies, there are 2 cookies stored in the browser by GA. One of them is simply called _ga, but the other one is called _ga_ + unique code for every user (for example: _ga_CPQBB2KVM4).

I cannot figure out a way to delete the cookie with the unique code, since I only know it's first 4 characters (I'm using Javascript).

I would be very grateful if you could help me with this!


Solution

  • You could just remove the cookie value using:

    function removeCookieValue(name) {
        document.cookie = name+'="";-1; path=/';
    }
    
    removeCookieValue('_ga')