0

I have a response header of set-cookie with the value of set-cookie: frontend=2j5mfe8nidhhmltlaoliu5bmj6; expires=Thu, 10-Sep-2020 22:52:25 GMT; Max-Age=86400; path=/; domain=www.shoepalace.com; httponly and I want to log just the part of the cookie after frontend= up to the ; (That would be 2j5mfe8nidhhmltlaoliu5bmj6)

const string = response.headers['set-cookie'] console.log(string) That logs this: [ 'frontend=0uhi7fj03fro4f5n2at4ev1t77; expires=Fri, 11-Sep-2020 01:15:47 GMT; Max-Age=86400; path=/; domain=www.shoepalace.com; HttpOnly', '__cf_bm=2d7abb53a603ff50426362615a2cba7c3bd0d58c-1599700547-1800-AVURmHeYokYbppItftnydR/xiAuOS75aQzUlJoxN/79VKKgYr9d7cx6DmgdSK4BbvjQ/pjC0+5lQXkLdn/QIdII=; path=/; expires=Thu, 10-Sep-20 01:45:47 GMT; domain=.shoepalace.com; HttpOnly; Secure; SameSite=None' ] const pairs = string.split(';') const obj = {} pairs.forEach(pair => { const split = pair.split('=') const key = split[0] const value = split[1] obj[key] = value }) console.log(obj.frontend) 

1 Answer 1

2

Something like this:

const cookies = [ 'frontend=0uhi7fj03fro4f5n2at4ev1t77; expires=Fri, 11-Sep-2020 01:15:47 GMT; Max-Age=86400; path=/; domain=www.shoepalace.com; HttpOnly', '__cf_bm=2d7abb53a603ff50426362615a2cba7c3bd0d58c-1599700547-1800-AVURmHeYokYbppItftnydR/xiAuOS75aQzUlJoxN/79VKKgYr9d7cx6DmgdSK4BbvjQ/pjC0+5lQXkLdn/QIdII=; path=/; expires=Thu, 10-Sep-20 01:45:47 GMT; domain=.shoepalace.com; HttpOnly; Secure; SameSite=None' ] let frontendValue cookies.forEach(cookie => { const pairs = cookie.split(';') pairs.forEach(pair => { const split = pair.split('=') const key = split[0] if (key === 'frontend') { frontendValue = split[1] } }) }) console.log(frontendValue)

  1. We split the string into an array after each ;
  2. We create a empty object/dictionary/map
  3. Loop through all the key-value pairs we got
  4. Split again on the =
  5. Read the keys and return the value for frontend
Sign up to request clarification or add additional context in comments.

6 Comments

Then I think you're editing the code example or there is some mismatch in the string. I've changed the code example to a snippet, you can run it and see it logs out 2j5mfe8nidhhmltlaoliu5bmj6
yeah got it, but now it says split() is not a funciton
Hehe its a little hard to guess what's wrong, when you change the code :) You gotta show some code or tell me what has changed, since my code is working, then you're editing it, it gives errors and I have no idea what you changed :D
Here it is: ``` const string = response.headers['set-cookie'] console.log(string) const pairs = string.split(';') const obj = {} pairs.forEach(pair => { const split = pair.split('=') const key = split[0] const value = split[1] obj[key] = value }) console.log(obj.frontend) ```
I edited the code of the main post to show what I have
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.