Cookie having "=" in value
I have to check whether cookie exist or not while making request. The problem is that Cookie value is having "=" in it for e.g.
....;username=firstName=Meet;....
Here cookie name is "username" and cookie value is "firstName=Meet". The pro开发者_C百科blem is when I try to get cookie from document.cookies. I am getting all the cookies after exploding the result using split function for ";".
For getting values I am exploding / splitting each value by "=" then this cookie value is coming till firstName only.
Any thoughts that I can get whole value as firstName=Meet.
thanks, Meet
// when you get a cookie string:
unescape(cookieData);
// when you set a cookie string:
escape(yourString);
If the cookie is being set on the server side, you need to urlencode the value, just as if it were a query string. If you're using PHP with setcookie, this should be done automatically for you. Actually, any decent library out there should urlencode the cookie values for you automatically.
The only way that the cookie value could've been set as username=firstName=Meet would be if you're sending the Set-Cookie header manually.
If you give more information on how the cookie is being set in the first place, that would help give a more accurate answer.
There are a few alternatives for looking up a single cookie in a known format from document.cookies. Here's a simplified case using a regular expression.
var expr = /(?:^|; )username=([^;]+)/i; //match "username=some_string_that_string_may_have_more=_in_it". Capture the part after the leading =. Does not capture the trailing ;
var cookie_match = document.cookie.match(expr);
var cookie_val;
if (cookie_match) {
cookie_val = cookie_match[1];
}
//result should be cookie_val = "firstName=Meet"
You can of course get all the cookies, by splitting document.cookie, as you were doing above, and if you're capturing a large number of cookies or writing a cookie access wrapper, that's a good idea. Just keep in mind that, when using sub-cookies, cookies will look like:
cookiename=cookiekey=cookievalue&key2=val2;
You want to use a regular expression or slice/indexOf to make sure you are only splitting each individual cookie on the first equal sign. You can then get individual name/value pairs by splitting first on the &
and then on =
if you want that level of detail.
A better solution now, in 2022, would be to use encodeURIComponent
and decodeURIComponent
.
For example,
let str = 'thisIsMyCookieWith=';
let encodedStr = encodeURIComponent(str);
console.log(encodedStr)
// thisIsMyCookieWith%3D
let decodedStr = decodeURIComponent(encodedStr);
console.log(decodedStr)
// thisIsMyCookieWith=
精彩评论