Get Cookie by Name

Get cookie value by name and change style DOM element

Image we have a cookie with language name and a div with myDiv id to change it's style to rtl if the language has set to arabic in the cookie:

<script>
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2){
return parts.pop().split(';').shift();
}
}
const isArabic = getCookie('language') === 'Arabic';
const myDiv = document.getElementById('myDiv')
if(isArabic){
myDiv.dir = isArabic ? 'rtl' : 'ltr';
}
</script>

Java: Is there a simple way to get cookie by name?

The logic (as suggested by Matt Ball in the comments) would be:

// ...
Map<String, Cookie> cookieMap = new HashMap<>();
for (Cookie cookie : cookies) {
cookieMap.put(cookie.getName(), cookie);
}

Cookie firstRequiredCookie = cookieMap.get("<NAME>");
// do something with firstRequiredCookie
Cookie nextRequiredCookie = cookieMap.get("<ANOTHER_NAME>");
// do something with nextRequiredCookie
// ...

What is the shortest function for reading a cookie by name in JavaScript?

Shorter, more reliable and more performant than the current best-voted answer:

const getCookieValue = (name) => (
document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)')?.pop() || ''
)

A performance comparison of various approaches is shown here:

https://jsben.ch/AhMN6

Some notes on approach:

The regex approach is not only the fastest in most browsers, it yields the shortest function as well. Additionally it should be pointed out that according to the official spec (RFC 2109), the space after the semicolon which separates cookies in the document.cookie is optional and an argument could be made that it should not be relied upon. Additionally, whitespace is allowed before and after the equals sign (=) and an argument could be made that this potential whitespace should be factored into any reliable document.cookie parser. The regex above accounts for both of the above whitespace conditions.

How to get a single cookie by name from response.Cookies() in Golang?

Response.Cookies() returns you a slice of all parsed http.Cookies. Simply use a loop to iterate over it and find the one that has the name you're looking for:

cookies := resp.Cookies()
for _, c := range cookies {
if c.Name == "wr_entry_path" {
// Found! Use it!
fmt.Println(c.Value) // The cookie's value
}
}

find a cookie by name then return the cookie including the value using javascript (no jquery)

First, you set the functions

function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

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;
}

function eraseCookie(name) {
createCookie(name,"",-1);
}

Then you just need to read and set it.

//Setting
createCookie('_ga','9saua9s8d89w',7);
//Reading
var x = readCookie('_ga')
if (x) {
//[do something with x]
}

EDIT
Via REGEXP

function readCookie(cookieName) {
var re = new RegExp('[; ]'+cookieName+'=([^\\s;]*)');
var sMatch = (' '+document.cookie).match(re);
if (cookieName && sMatch) return unescape(sMatch[1]);
return '';
}

Then

var x = readCookie('_ga');
if (x) {
//[do something with x]
}

OR, just the REGEXP code

var cookie = "_ga"
var re = new RegExp('[; ]'+cookie+'=([^\\s;]*)');
var cookieVal = unescape((' '+document.cookie).match(re)[1]);

console.log(cookieVal); //GA1.2.116321536.1432242890


Related Topics



Leave a reply



Submit