0

I have a group of cookies that start with the same name "order" each new cookies from this group is added+1 to each new cookies so for example "order1", "order2" and so on.

How could I check if "order3" exist without checking if order1 and two exist?

The reason I ask is because there could be an unlimited number of cookies with name "order.." but in the next minute there might be only one "order12" now if I need to check if "order12" exist I do the following while loop. I just dont think this is the most efficient way of doing it.

var i = 1;
while(true){
    if(document.cookie.indexOf("order"+i+"=") >=0){//check if order number is empty 
       i++;
       //Do something not smart!
  • Check this: https://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie – Sertage Nov 08 '17 at 09:23

1 Answers1

0

Just do it without loop:

if(document.cookie.indexOf("order12=") > -1) {
  // yeah! it exists
}

or if that number needs to be dynamic:

var numberToCheck = 12;
if(document.cookie.indexOf("order" + numberToCheck + "=") > -1) {
  // do stuff
}

Since I don't know what you actually want to do with the cookies. Here are some approaches using regex you can use without knowing the actual numbers:
Assuming your cookie looks like this 'order1=foo;order10=bar;asdf=abc;order3=foobar;'

To just get all "orderX" values with match

var regEx = /order\d+=/g;
var cookies = document.cookie.match(regEx);
// cookies = ['order1=', 'order10=', 'order3=']

Or retrieve some more information with exec:

var regEx2 = /order(\d+)=(.[^;]+)/g;
var numbers = [];
var completeCookie = [];
var values = [];
var myArray;
while ((myArray = regEx2.exec(document.cookie)) !== null) {
  completeCookie.push(myArray[0]);
  numbers.push(myArray[1]);
  values.push(myArray[2]);
}
// completeCookie = ['order1=foo', 'order10=bar', 'order3=foobar']
// numbers = ['1', '10', '3']
// values = ['foo', 'bar', 'foobar']
zwif
  • 195
  • 3
  • 13
  • The problem with that is I just gave an example with "order12", I cant never know what number it will be which is why i had it in a loop. I cant just set a specific number to be check with as that number is dynamic and will change constantly. –  Nov 08 '17 at 09:31
  • so you want to do some stuff for *every*(?) orderX cookie available, without knowing what X are actually are available? – zwif Nov 08 '17 at 09:40