How to make a browser display special symbols in a cookie

alex38

New member
Hi,

I have a js code what can parse a cookie. The cookie looks like this:

cookies2.jpg
How to I can make such the cookie?
I tried entering multiple key-value pairs into the value field. But special symbols such the equal symbol (=) display in %xx format.
cookie3.jpg
 
Hi,

I have a js code what can parse a cookie. The cookie looks like this:

View attachment 993
How to I can make such the cookie?
I tried entering multiple key-value pairs into the value field. But special symbols such the equal symbol (=) display in %xx format.
View attachment 994
Try this:

Code:
// Function to set a cookie with special symbols
function setCookie(name, value, days) {
    const expires = new Date(Date.now() + days * 864e5).toUTCString();
    document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}; expires=${expires}; path=/`;
}

// Function to get a cookie by name
function getCookie(name) {
    return document.cookie.split('; ').reduce((acc, cookie) => {
        const [key, val] = cookie.split('=');
        return key === decodeURIComponent(name) ? decodeURIComponent(val) : acc;
    }, null);
}

// Example usage
setCookie('specialSymbol', '😊✨', 7); // Setting a cookie with special symbols
const retrievedValue = getCookie('specialSymbol'); // Retrieving the cookie
console.log(retrievedValue); // Output: 😊✨

In the provided code, we have defined two functions: setCookie and getCookie.

  1. setCookie(name, value, days): This function is responsible for creating a cookie. It takes three parameters:
    • name: The name of the cookie.
    • value: The value to be stored in the cookie, which can include special symbols.
    • days: The number of days until the cookie expires.
    • Inside the function, we calculate the expiration date and format it to UTC string. The encodeURIComponent function is used to ensure that both the name and value are properly encoded, allowing special symbols to be stored without issues.
  2. getCookie(name): This function retrieves the value of a cookie by its name. It splits the document.cookie string into individual cookies and checks if the specified cookie name matches. If a match is found, it decodes the value using decodeURIComponent and returns it.
  3. Example Usage: We demonstrate how to set a cookie with special symbols (in this case, an emoji and a sparkle symbol) and then retrieve it. The retrieved value is logged to the console, confirming that the special symbols are correctly stored and retrieved.
 
Back
Top