0

I'm trying to call a bunch of cookies I have stored back onto a page. There are multiple ones with names like todo-0, todo-1 (you get the idea). So, I'm trying to figure out a way of calling all cookies that's name starts with 'todo-' and then print the value of that cookie to my page inside a table.

I was kinda hoping it would be as simple as:

if (document.cookie.name.match(/^todo-/)) {
    todoTable.insertAdjacentHTML('beforeend', document.cooke.value);
}

But I get an error saying no method 'match'.

Any ideas about the best way to root through multiple cookies and fetch ones the start with todo- ?

1
  • there is no such thing like document.cookie.name, document.cookie contains string with all cookies assigned to document. Commented Jan 9, 2013 at 13:37

1 Answer 1

1

You will have to do something like this:

var myCookies = document.cookie.split(";");

for(var i = 0; i < myCookies.length; i++)
{
    var cookie = myCookies[i].trim().split("=");

    if(cookie[0].indexOf("todo-") === 0) {
        todoTable.insertAdjacentHTML('beforeend', decodeURIComponent(cookie[1]));
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

you should decode value first as it is url encoded decodeURIComponent(cookie[1]) (same thing with cookie names, but in todo- there is nothing to decode so that step can be omitted in this case)
and String.trim is supported only by modern browsers - just a notice ;)
This is great guys! It didn't seem to work at first, but adding an alert in the if statement shows that each one is being picked up correctly. However the content isn't being placed into the table at all, kinda weird. Seems to be the decodeURIComponent(cookie[1]) part, it I just have it say cookie it shows up. Is this expected?
Just noticed a potential issue with this approach however. Inside the cookie is some HTMl with = in it! Ofc this code gets rid of all those = so the code doesn't display correctly :/ Also, it displays the name of the cookie, is there a way to just call the value?
Never mind! I wasn't encodingURI in the first place. All sorted, amazing guy, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.