Broken string in cookie after ampersand (javascript)

I have a little problem that the line I am reading from the cookie breaks after the ampersand. So, for example, the line "hello and world" will just display "hello". It is a string that is a shortcode and is converted to something more meaningful using a toggle function and then displayed in a text box. The switch function works fine, but obviously if it doesn't read the full line from the cookie in the first place then it won't be able to find the shortcode in the switch function.

I am currently using the following code to read the cookie ...

document.example.textfield.value = switchFunction(unescape(coalesce($_GET['example'],readCookie('_cookie'))));

      

If you need me to provide more information, please let me know. This is my first post here, so apologize in advance if anything is wrong or unclear.

Thank you for your help.

EDIT

The switchFunction looks like this.

function SwitchFuntion(Code){
    switch(Code){
       case 'text & text, Text' : return 'new meaningful text'; break;
    }
}

      

etc....

The readCookie function looks like this:

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

      

+2


source to share


1 answer


I think I am having a similar problem in an ASP.NET MVC application.

When I store a string containing ampersands in a cookie / name pair, it is actually split into multiple name / value pairs

eg. an attempt to save ("value","cookiedata123&book=2&page=0")

will result in three pairs of name values "value"="cookiedata123"; "book"="2"; and "page"="0"

.



I resolved this by url. Encode the value just before writing to the cookie and decode it as soon as I read it. In .net, the calls look like this:

// Encode
return System.Web.HttpUtility.UrlEncode(cookieData);

// Decode
return System.Web.HttpUtility.UrlDecode(encodedCookieData);

      

This applies to any ampersands, equivalent signs, etc. that might cause problems. See this post here for information on the characters allowed in cookies. Allowed characters in cookies

+4


source







All Articles