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.Cookie
s. 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
JavaScript: Difference Between .Foreach() and .Map()
JavaScript Add Leading Zeroes to Date
How to Access a Dom Element in React? What Is the Equilvalent of Document.Getelementbyid() in React
Prevent Address-Bar Hiding in Mobile Browsers
How to Set Prefixed CSS3 Transitions Using JavaScript
Example of How to Load Static CSS Files from Node_Modules Using Webpack
How to Execute JavaScript in Ruby Written Webdriver Test
What's the Best Way to Inject One Service into Another in Angular 2 (Beta)
How to Parse a CSV String With JavaScript, Which Contains Comma in Data
Indexof Method in an Object Array
How to Post a File from a Form With Axios
Leaflet Map Not Displayed Properly Inside Tabbed Panel
Can Jquery Change CSS Style Definition? (Not Individual CSS of Each Element)
Vertical Centering Variable Height Image While Maintaining Max-Width/Height
Google Map Custom Marker with CSS Rounded Corner
Problem Deploying Rails 3.1 Project to Heroku: Could Not Find a JavaScript Runtime