0

I'm trying to create a simple cookie using javascript . But for some reason , json.stringify doesnt seem to work

i have the below object

var text = JSON.stringify({username: req.user.username})

which i send back as the cookie

res.cookie('user',text)

however , the client side stores the cookie in this format

user=%7B%22username%22%3A%22Kannaj%22%7D

how do i escape the '%' characters and store it as a stringified JS object?

1
  • 1
    The % characters are escape sequences. The storage is fine. You just need to unescape it when you want to read the data. Commented Jun 21, 2016 at 11:57

2 Answers 2

1

decodeURIComponent

decodeURIComponent('%7B%22username%22%3A%22Kannaj%22%7D')
//returns
'{"username":"Kannaj"}'

As noted by Quentin:

The storage is fine. You just need to unescape it when you want to read the data

Sign up to request clarification or add additional context in comments.

3 Comments

Could i do this on the server side?
Nope, it's a protocol thing, you can unescape on client
@VatsalPathak Replaces each escape sequence in the encoded URI component with the character that it represents. So yeah, it only returns strings, as only strings has replace method
0

Use decodeURLComponent, it accepts an encoded component of a Uniform Resource Identifier.

decodeURIComponent("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
// "JavaScript_шеллы"

Comments

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.