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:
cookie1=value
cookie2=value2; Expires=Thu
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
You can try this:
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.
Perhaps you could first match the format using a regex, and then split on
,
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 rightRegex demo
Or a bit broader match and and shorter pattern:
Regex demo