PDA

View Full Version : Manipulating Cookies with JS



JBottero
05-07-2009, 05:52 AM
I am new to JavaScript, so there is probably a better way to do this...

Suppose I have a cookie consisting of a series of numbers, and a have one of those numbers I want to delete from the cookie...

Cookie (example): 12|56|23|67

Number to delete ( idToDelete ): 23

Output: 12|56|67


function delfslist()
{
var cookiename = "fslist";
var idToDelete = document.getElementById('fsid').value;
var idArray = null;
var idArrayLen = null;
var cookiecontents = null;
var newcookiecontents = null;
// Get the cookie
cookiecontents = get_cookie ( cookiename );
// If there is a cookie, do this...
if (cookiecontents != null) {
// Split the cookie into an array.
idArray = cookiecontents.split("|");
// Get the array count.
idArrayLen = idArray.length;
// If there is only ONE, delete the whole cookie.
if (idArrayLen == 1)
{
// If only one ID in cookie, delete it.
delete_cookie ( cookie_name )
} else {
// Loop through array...
for (i=0; i < idArrayLen; i++) {
if (( idArray[i] != idToDelete ) && ( newcookiecontents != null )) {
newcookiecontents = newcookiecontents+"|"+idArray[i];
} else if ( idArray[i] != idToDelete ) {
newcookiecontents = idArray[i];
}
}
}
set_cookie(cookiename, newcookiecontents);
}
}

Set_cookie and get_cookie are functions that do what they sound like.

So, my question is: Is there a better way to do this?

JBottero
05-07-2009, 10:26 PM
I'm wondering if there might be a way to apply Regular Expressions to this problem?

codeexploiter
05-08-2009, 07:37 AM
Try this one


function delfslist() {
var cookieName = "fslist";
var idToDelete = document.getElementById('fsid').value;
var cookiecontents = null;
var idArray;
cookiecontents = get_cookie(cookiename); // If there is a cookie, do this...
if (cookiecontents !== null) {
idArray = cookicontent.split("|");
for (var i = 0; i < idArray.length; i++) {
if (idArray[i] === idToDelete) {
idArray.splice(i, 1);
}
}
cookiecontents = idArray.join("|");
if (cookiecontents !== "") {
set_cookie(cookiename, cookiecontents);
}
}
}

vwphillips
05-08-2009, 11:00 AM
posted in error