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.
The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.
JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies that apply to the current web page.
The RegEx is used with the replace() method to replace all the line breaks in string with <br>. The pattern /(\r\n|\r|\n)/ checks for line breaks.
The document. cookie attribute simply returns a string containing a semicolon and a space separated list of all cookies (i.e. name=value pairs, for example, firstName=Fabulous; lastName=Designs; ). This string does not include any of the cookie's characteristics, such as expires, path, domain, and so on.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With