6

I'm trying to save the value of a textarea into a cookie using Javascript.

The problem comes when the user enters multiple lines. Only the first line is saved and subsequent directives are ignored.

e.g.

var myText = $('#mytextarea').val();
document.cookie = "mycookie=" + myText + "; path=/;"

if myText contains the \n character which it does if the user entered multiple lines in the textarea field, then not only are the rest of the lines not stored in the cookie, but the path=/; is ignored.

1
  • 1
    You might need to double-escape the backslash so you're storing \\n in the string. Then when reading the cookie process it back from \\n => \n Commented Jul 3, 2018 at 0:24

2 Answers 2

10

Further to my comment about escaping the newline, the MDN cookie documentation has this note in the Write a new cookie section:

The cookie value string can use encodeURIComponent() to ensure that the string does not contain any commas, semicolons, or whitespace (which are disallowed in cookie values).

You can then use decodeURIComponent() when reading the cookie value back to get the original text.

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

Comments

1

What I do is replacing the line breaks "\n" with another character, like the "\" (backslash), that I'm sure will not be used.

var myText = $('#mytextarea').val();
var myCookieValue = myText.split('\n').join('\\');
document.cookie = "mycookie=" + myCookieValue + "; path=/;"

And when you read the cookie, just make the reverse conversion:

var cookie = rawValue.split('\\').join('\n');

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.