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?
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() || ''
)
This regex idea is from here
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 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 rule and pratice
regex test
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:
document.cookie
is how you can reach the cookie, which is a string with a format where ;
separates the cookie items.split(';')
we create an object out from document.cookie
that will hold all the raw cookie items of the format of name=value
forEach
we loop through the arrayrawItem
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 onforEach
is a so-called callback function, that is, a function that will be called for each item in the arrayrawItem
starting from its very beginning up until the first (!!!) occurrence of =
and assign it to name
name
and the fact that just after the name
there is a =
, we know where the position of the value
is, so we get that substring and assign it to value
myCookies
object, identified by name
and we assign the value of value
to itconsole.log
the result to check its correctness, this line is unnecessary when you apply this solutionOne 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With