admin管理员组

文章数量:1322838

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

The problem es 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.

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

The problem es 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.

Share Improve this question asked Jul 3, 2018 at 0:22 komodospkomodosp 3,6584 gold badges36 silver badges68 bronze badges 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 – Sly_cardinal Commented Jul 3, 2018 at 0:24
Add a ment  | 

2 Answers 2

Reset to default 10

Further to my ment 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 mas, 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.

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');

本文标签: How to save cookie with line break in JavascriptStack Overflow