Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save cookie with line break in Javascript?

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.

like image 202
colmde Avatar asked Jul 03 '18 00:07

colmde


People also ask

How do you insert a line break in JavaScript?

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.

Can we manipulate cookie using JavaScript?

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.

How do I replace all line breaks in a string with br /> elements?

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.

What is cookie return?

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.


1 Answers

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.

like image 126
Sly_cardinal Avatar answered Sep 18 '22 00:09

Sly_cardinal