I have cookies: 'name=112'
how do I get the name value from it?
There is split()
method, that cuts strings, but is there a better way to get a cookie value?

- 16,592
- 6
- 46
- 58

- 47
- 6
-
2If you control the code where the cookie is set, you could encode it as JSON. This is easier to code correctly and also more extensible. – Thomas Oct 11 '22 at 09:39
2 Answers
Hope this can help
Use the regular expression (regex) and match() method to get the cookie value
The match()
will return a array that fit the regex rule you gave.
And pop() will pop the last one in array.
(^|;)
means a group which start from a semicolon or not
([^;]+)
means a group which any text except semicolon
And let your cookie name inside these two regular repression ( (^|;)\\s*
and \\s*=\\s*([^;]+)
) will have a ;[cookie name]=[any value];
regex pattern.
It will return an array that matchs regex pattern and captured groups.(See match()'s definition). So the second group(cookie value) will be the last one in array. Then pop it out.
/**
* get cookie value by name
* @param {string} name cookie name
*/
const getCookieValue = (name) => (
document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || ''
)
Set cookie
An other function which can help me to set cookie
/**
* set cookie with name value and life time
* @param {string} name cookie name
* @param {string} value cookie value
* @param {number} expireTime seconds
*/
const setCookie = async (name, value, expireTime = 0) => {
const expires = (new Date(Date.now() + expireTime * 1000)).toUTCString();
document.cookie = `${name}=${value}; expires=` + expires + ";path=/;"
}
Combine and export
Combine this two function into one object and export it in another JS file. Can make your code clean.
var cookieManager = cookieManager || {};
/**
* get cookie value by name
* @param {string} name cookie name
*/
cookieManager.getCookieValue = (name) => (
document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || ''
)
/**
* set cookie with name value and life time
* @param {string} name cookie name
* @param {string} value cookie value
* @param {number} expireTime seconds
*/
cookieManager.setCookie = async (name, value, expireTime = 0) => {
const expires = (new Date(Date.now() + expireTime * 1000)).toUTCString();
document.cookie = `${name}=${value}; expires=` + expires + ";path=/;"
}
export default cookieManager;
regex test website and pratice

- 615
- 1
- 7
- 23
Since you have not provided a definition of what "better" is according to you and why you dislike splitting the cookie, I will present the approach with split
, arguing that it's better than you would think:
var myCookies = {};
document.cookie.split(';').forEach(rawItem => {
var name = rawItem.substring(0, rawItem.indexOf("="));
var value = rawItem.substring(name.length + 1);
myCookies[name] = value;
});
console.log(myCookies);
Explanation:
- we create an empty object that will store the cookies
document.cookie
is how you can reach the cookie, which is a string with a format where;
separates the cookie items- by calling
.split(';')
we create an object out fromdocument.cookie
that will hold all the raw cookie items of the format ofname=value
- by calling
forEach
we loop through the array - at each step,
rawItem
will be the cookie item. At the first step it's the first cookie item, at the second step it's the second cookie item and so on - the whole parameter given to
forEach
is a so-called callback function, that is, a function that will be called for each item in the array - therefore, for each item
- we get the part of the
rawItem
starting from its very beginning up until the first (!!!) occurrence of=
and assign it toname
- knowing the length of the
name
and the fact that just after thename
there is a=
, we know where the position of thevalue
is, so we get that substring and assign it tovalue
- finally, we create a data member for our
myCookies
object, identified byname
and we assign the value ofvalue
to it
- we get the part of the
- finally, we
console.log
the result to check its correctness, this line is unnecessary when you apply this solution
Why would this be bad?
One may be concerned in the difficulty of processing the items. As a matter of fact, even though it's subjective, but this solution seems to be very simple to me and I have difficulty imagining a simpler solution (apart from using a third-party library that would be a function call, but, under the hood that solution would not be significantly easier, so we have the choice of creating that function ourselves or using a similarly implemented function that was created by someone else).
Another possible concern may be regarding performance. Arguably, the cookie will not be as large as it would really cause a problem and solving performance problems prematurely is something we need to discourage beginners from doing. Yet, how would we decrease the complexity of the algorithm? We will need to split the items somehow and we will need to differentiate what the name
or value
is somehow.

- 64,414
- 37
- 100
- 175