skip to Main Content

I’m working with Serverless framework (Javascript) and it requires me to split a single Set-Cookie into an array of cookies for it to be correctly set on the client. Why? No idea, but this seems to be what is going on.

I do not have access to the code that generates the Set-Cookies string, so I have to manually split it into an array.

My string looks like this:

cookie1=value, cookie2=value2; Expires=Thu, 06 Jul 2023 14:45:25 GMT;

You can probably guess my issue, if I do string.split(', ') my string is split in three:

  1. cookie1=value
  2. cookie2=value2; Expires=Thu
  3. 06 Jul 2023 14:45:25 GMT;

I’ve Googled but I cannot find an already existing answer anywhere. I know I can probably resolve this with Regex, but it’s far too complex for me to figure it out.

2

Answers


  1. You can try this:

    let aList = [];
    let s = 'cookie1=value, cookie2=value2; Expires=Thu, 06 Jul 2023 14:45:25 GMT;'
    for (const match of s.matchAll(/cookied+=([^;,]+)(?:,|;)/g)) {
          console.log(`matched: ${match[1]}`);
          aList.push(match[1])
    } 
    console.log(aList)
    //(2) ['value', 'value2']
    

    First part matches cookie word followed by a digit and an equal sign.
    Capture group matching one or more characters that are that are not semicolon or comma. It captures the value of cookie.

    Login or Signup to reply.
  2. Perhaps you could first match the format using a regex, and then split on ,

    [^;,=s]+=[^;,=s]+(?:, [^;,=s]+=[^;,=s]+)+(?=;)
    

    The pattern matches:

    • [^;,=s]+ Match 1+ chars other than ; , = or a whitespace char
    • = Match literally
    • [^;,=s]+ Same as the first pattern
    • (?:, [^;,=s]+=[^;,=s]+)+ Repeat 1+ times , followed by the whole first pattern
    • (?=;) Positive lookahead, assert ; to the right

    Regex demo

    Or a bit broader match and and shorter pattern:

    [^=s]+=S+(?:, [^=s]+=S+)+(?=;)
    

    Regex demo

    const regex = /[^;,=s]+=[^;,=s]+(?:, [^;,=s]+=[^;,=s]+)+(?=;)/;
    const s = `cookie1=value, cookie2=value2; Expires=Thu, 06 Jul 2023 14:45:25 GMT;`;
    const m = s.match(regex);
    if (m) {
      console.log(m[0].split(", "));
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search