Retrieve Cookie Content - javascript

I'm trying tof ind a way to retrieve the content of a cookie in javascript.
Let's assume that the cookie is named "Google"
and lets also assume content of this cookie is just "blah"
I've been looking online and all I find are complex functions, and what I was wondering if there is a simple one line such code that retreives the value of the content in a cookie'
such as -
var myCookie = cookie.content('Google');
I don't want long parsers to check for various cookies or if the cookies have multiple value or whatever..Thanks!

QuirksMode has a very simple, but effective cookie script.
var Google = readCookie("Google"); // Google is now "blah"

Not exactly a simple one-line solution but close!
var results = document.cookie.match ( '(^|;) ?' + cookiename + '=([^;]*)(;|$)' );
if ( results ) myCookie = decodeURIComponent(results[2] ) ;

You'll have to parse the cookie jar yourself but it isn't that hard:
var name = 'the_cookie_you_want';
var value = null;
var cookies = document.cookie.split(/\s*;\s*/);
for(var i = 0; i < cookies.length; i++) {
if(cookies[i].substring(0, name.length + 1) == (name + '=')) {
value = decodeURIComponent(cookies[i].substring(name.length + 1));
break;
}
}

You can use document.cookie, or document.cookie.split(';') to get a full list of key/values.

In javascript all cookies are stored in a single string. THe cookies are separated by a ;
A possible function to read cookies is:
function readCookie(myCookieName)
{
if (document.cookie.length > 0)
{
var start = document.cookie.indexOf(myCookieName + "=");
if (start != -1)
{
start = start + myCookieName.length + 1;
var end = document.cookie.indexOf(";",start);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(start ,end ));
}else{
return "";
}
}
return "";
}

Related

getSheetByName() returns null in google script

I am using the following code to try and set the sheet title to the name of the form that I have just connected to it with the code. However, I keep getting that the sheet name returning as "null", even though the debugger and physically looking at the sheet indicate that the name (Form Responses 1) is there. Any suggestions?
var data = SpreadsheetApp.create('C Term 2017 Unit 0');
var idlog = data.getId();
var title = 'RST.5';
for (i = 1; i <= 7; i++) {
var dataset = SpreadsheetApp.openById(idlog);
var sname = ('Form Responses ' + i);
var active = dataset.getSheetByName(sname);
active.setName(title);
}
Thank you!
Before
var sname = ('Form Responses ' + i);
add
var i = 1;
Maybe the variable i is not correctly converted to a string?
You could try converting i to string explicitly:
var sname = ('Form Responses ' + i.toString());

document.cookie prints long string value [duplicate]

I found two functions to get cookie data with Javascript, one on w3schools.com and one on quirksmode.org
I would like to know which one I should use?
For example I believe I read somewhere that there was a problem with some browsers splitting the ; semicolon?
w3schools:
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
quirksmode:
function readCokie(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;
}
The function from W3CSchool is wrong. It fails if there are multiple cookies that have the same suffix like:
ffoo=bar; foo=baz
When you search for foo it will return the value of ffoo instead of foo.
Now here is what I would do: First of all, you need get to know the syntax of how cookies are transported. Netscape’s original specification (there are only copies available like this one at haxx.se) uses semicolons to separate multiple cookies while each name/value pair has the following syntax:
NAME=VALUE
This string is a sequence of characters excluding semi-colon, comma and white space. If there is a need to place such data in the name or value, some encoding method such as URL style %XX encoding is recommended, though no encoding is defined or required.
So splitting document.cookie string at semi-colons or commas is a viable option.
Besides that, RFC 2109 does also specify that cookies are separated by either semi-colons or commas:
cookie = "Cookie:" cookie-version
1*((";" | ",") cookie-value)
cookie-value = NAME "=" VALUE [";" path] [";" domain]
cookie-version = "$Version" "=" value
NAME = attr
VALUE = value
path = "$Path" "=" value
domain = "$Domain" "=" value
Although both are allowed, commas are preferred as they are the default separator of list items in HTTP.
Note: For backward compatibility, the separator in the Cookie header
is semi-colon (;) everywhere. A server should also accept comma (,)
as the separator between cookie-values for future compatibility.
Furthermore, the name/value pair has some further restrictions as the VALUE can also be a quoted string as specified in RFC 2616:
attr = token
value = token | quoted-string
So these two cookie versions need to be treated separately:
if (typeof String.prototype.trimLeft !== "function") {
String.prototype.trimLeft = function() {
return this.replace(/^\s+/, "");
};
}
if (typeof String.prototype.trimRight !== "function") {
String.prototype.trimRight = function() {
return this.replace(/\s+$/, "");
};
}
if (typeof Array.prototype.map !== "function") {
Array.prototype.map = function(callback, thisArg) {
for (var i=0, n=this.length, a=[]; i<n; i++) {
if (i in this) a[i] = callback.call(thisArg, this[i]);
}
return a;
};
}
function getCookies() {
var c = document.cookie, v = 0, cookies = {};
if (document.cookie.match(/^\s*\$Version=(?:"1"|1);\s*(.*)/)) {
c = RegExp.$1;
v = 1;
}
if (v === 0) {
c.split(/[,;]/).map(function(cookie) {
var parts = cookie.split(/=/, 2),
name = decodeURIComponent(parts[0].trimLeft()),
value = parts.length > 1 ? decodeURIComponent(parts[1].trimRight()) : null;
cookies[name] = value;
});
} else {
c.match(/(?:^|\s+)([!#$%&'*+\-.0-9A-Z^`a-z|~]+)=([!#$%&'*+\-.0-9A-Z^`a-z|~]*|"(?:[\x20-\x7E\x80\xFF]|\\[\x00-\x7F])*")(?=\s*[,;]|$)/g).map(function($0, $1) {
var name = $0,
value = $1.charAt(0) === '"'
? $1.substr(1, -1).replace(/\\(.)/g, "$1")
: $1;
cookies[name] = value;
});
}
return cookies;
}
function getCookie(name) {
return getCookies()[name];
}
Yes, the W3Schools solution is incorrect.
For those that would like it, here is a simpler solution that works. It just prepends a space so the single call to indexOf() only returns the correct cookie.
function getCookie(c_name) {
var c_value = " " + document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_value = null;
}
else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
This, from w3schools, is incorrect in that it may lead to getting the wrong cookie:
c_start = document.cookie.indexOf(c_name + "=");
If you go looking for a cookie named foo (which we'll suppose is an existing cookie) then somewhere in document.cookie will be the string foo=bar.
However, there's no guarantee there won't also be the string xfoo=something. Notice that this still contains the substring foo= so the w3schools code will find it. And if the xfoo cookie happens to be listed first, you'll get back the something value (incorrectly!) instead of the expected bar.
Given the choice between two pieces of code, never go with the one that's fundamentally broken.
All of the code shown above is BROKEN. The two common problems are (1) the getcookie function may return the wrong value if one cookie name is a proper suffix of another cookie name; and (2) the setcookie function does not protect the cookie value, which means that if the cookie value includes (for example) a ";" then all the cookies are corrupted and cannot be parsed.
TL;DR Use this well-written library instead:
https://github.com/js-cookie/js-cookie
Here is my version, it covers the edge case of quoted values.
function getCookies() {
const REGEXP = /([\w\.]+)\s*=\s*(?:"((?:\\"|[^"])*)"|(.*?))\s*(?:[;,]|$)/g;
let cookies = {};
let match;
while( (match = REGEXP.exec(document.cookie)) !== null ) {
let value = match[2] || match[3];
cookies[match[1]] = decodeURIComponent(value);
}
return cookies;
}

New value for cookie appended

This javascript code
function writeCookie(CookieName, CookieValue, CookieDuration) {
var expiration = new Date();
var now = new Date();
expiration.setTime(now.getTime() + (parseInt(CookieDuration) * 60000));
document.cookie = CookieName + '=' + escape(CookieValue) + '; expires=' + expiration.toGMTString() +
'; path=/';
}
function readCookie(CookieName) {
if (document.cookie.length > 0) {
var beginning = document.cookie.indexOf(CookieName + "=");
if (beginning != -1) {
beginning = beginning + CookieName.length + 1;
var ending = document.cookie.indexOf(";", beginning);
if (ending == -1) ending = document.cookie.length;
return unescape(document.cookie.substring(beginning, ending));
}
else {
return "";
}
}
return "";
}
var before = readCookie('totali');
var after = before + 1;
writeCookie('totali', after, 43200);
Should read cookie 'totali', add "1" to its value and then rewrite the new value.
The first time I run the code, cookie becomes "1", but the second time becomes "11", the third "111" and so on.
What could be the problem?
You are concatenating strings. Convert the value read from the cookie into a number before attempting to add it:
var after = parseInt(before) + 1;
But the problem is that the first time you read the cookie, the value is an empty string, and parseInt("") will be NaN. In this case, you have to check before you use it. This will assign 1 if the function returns an empty string, or the value stored in the cookie + 1 if not:
var after = (before.trim() == "") ? 1 : parseInt(before) + 1;
This assumes you never place anything other than a number in that totali cookie.
See http://jsfiddle.net/9rLZP/3/ (I changed the name of the cookie, so you can see the change without having to remove the previous cookie)

I need to get the last two value after dot using javascript split

I am getting the results like demo.in,demo.co.in,demo.tv,demo.org.in
I need to split the extension separately using JavaScript split function
var vsp = i.split(".");
this is my code I will get the result as
demo,in demo,co,in
but I need to get the extension separately
Working fiddle(demo version)
var values = [
"demo.in",
"demo.co.in",
"demo.tv","demo.org"
];
var results = [];
// iterate through the values
for (var i = 0, len = values.length; i < len; i++) {
// Split the parts on every dot.
var parts = values[i].split(".");
// Remove the first part (before the first dot).
parts = parts.slice(1, parts.length);
// Join the results together
results.push(parts.join("."));
};
console.dir(results); // all done
// Nicely display the values for the OP:
for (var i = 0, len = results.length; i < len; i++) {
document.body.innerHTML += (i + 1) + ": " + results[i] + "<br />";
};
I have no idea what you want, so here's some functions to cover the likely cases:
var s = 'demo.co.in'
// Return everything before the first '.'
function getExtension(s) {
var m = s.match(/^[^.]+/);
return m? m[0] : '';
}
alert(getExtension(s)); // demo
// Return everything after the last '.'
function getExtension2(s) {
var m = s.match(/[^.]+$/);
return m? m[0] : '';
}
alert(getExtension2(s)); // in
// Return everything after the first '.'
function getExtension3(s) {
return s.replace(/^[^.]+\./, '');
}
alert(getExtension3(s)); // co.in
I could not understand exactly .. "the extension" . You can try like below code
var urls = "demo,demo.in,my.demo.co.in,demo.tv,demo.org.in"
.split(',');
var splited = urls.reduce( function( o, n ){
var parts = n.split( '.' );
o[ n ] = (function(){
var ext = [];
while( !(parts.length == 1 || ext.length == 2) ) {
ext.unshift( parts.pop() );
};
return ext.join('.');
}());
return o;
}, {} );
console.log( JSON.stringify( splited ) );
which prints
{
"demo":"",
"demo.in":"in",
"my.demo.co.in":"co.in",
"demo.tv":"tv",
"demo.org.in":"org.in"
}
process result using
for( var i in splited ) {
console.log( i, splited[i]);
}
Try this:
var vsp = i.split(".");
for(var i=0; i< vsp.length; i++){
if(i !== 0){ //leaving the first match
// do something with vsp[i]
}
}
I hope you are not considering www also. :). If so, then keep i>1 instead of i !== 0.
There are several ways to do it (probably none as easy as it should be). You could define a function like this:
function mySplit(str, delim) {
var idx = (str.indexOf(delim) == -1) ? str.indexOf(delim) : str.length;
return [str.substr(0,idx), str.substr(idx)];
}
And then call it like: var sp = mySplit(i, ".");
You can also use lastIndexOf, which returns the location of the last . and from there you can get the rest of the string using substring.
function getExtension(hostName) {
var extension = null;
if(hostName && hostName.length > 0 && hostName.indexOf(".") !== -1) {
extension = hostName.substring(hostName.lastIndexOf(".") + 1);
}
return extension;
}
From there, you can use this function in a loop to get the extensions of many host names.
Edit Just noticed the "last two values" part in the title :) Thanks #rab

Extract domain name suffix from any url

I have a url in string format like this :
str="http://code.google.com"
and some other like str="http://sub.google.co.in"
i want to extract google.com from first one, and google.co.in from second string .
what i did is :
var a, d, i, ind, j, till, total;
a = document.createElement('a');
a.href = "http://www.wv.sdf.sdf.sd.ds..google.co.in";
d = "";
if (a.host.substr(0, 4) === "www.") {
d = a.host.replace("www.", "");
} else {
d = a.host;
}
till = d.indexOf(".com");
total = 0;
for (i in d) {
if (i === till) {
break;
}
if (d[i] === ".") {
total++;
}
}
j = 1;
while (j < total) {
ind = d.indexOf(".");
d = d.substr(ind + 1, d.length);
j++;
}
alert(d);
My code works but it works only for ".com" , it doesnt work for others like ".co.in","co.uk" till i specify them manually , Can anyone tell me the solution for this ? I dont mind even i need to change the full code, but it should work . Thanks
The only current practical solution (and even that doesn't work 100%) is to refer to the Public Suffix List in your code, and synchronise with that list as required.
There is no algorithm that can look at a domain name and figure out which part is the "registered domain name" and which parts are subdomains. It can't even be done by interrogating the DNS itself.
Regular expressions are quite powerful for such problems.
https://regex101.com/r/rW4rD8/1
The code below should fit this purpose.
var getSuffixOnly = function (url) {
var normalized = url.toLowerCase();
var noProtocol = normalized.replace(/.*?:\/\//g, "");
var splittedURL = noProtocol.split(/\/|\?+/g);
if (splittedURL.length > 1){
noProtocol = splittedURL[0].toString().replace(/[&\/\\#,+()$~%'":*?<>{}£€^ ]/g, '');
}
var regex = /([^.]{2,}|[^.]{2,3}\.[^.]{2})$/g;
var host = noProtocol.match(regex);
return host.toString();
};
getSuffixOnly(window.location.host);

Categories

Resources