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.
-
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
2 Answers
Reset to default 10Further 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
版权声明:本文标题:How to save cookie with line break in Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742117353a2421529.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论