How to handle \ n, \ r and \ r \ n on different operating systems?

What is the correct way to handle line feeds on Windows, Mac, and Linux. Let's say I have a simple web application that has a text box, and I need to make a line that separates each new line. Is it safe to convert \ r \ n and \ r to \ n before processing the contents of the text field, or do I need to determine which OS the user is on and apply the conditional operator to each?

Code example

var content = $('textarea').val(); content = content.replace(/\r\n|\r|\n/gm, "\n"); content = content.split("\n"); // Do Something content = content.join("\n"); // Update content $('textarea').val(content); 
+5
source share
1 answer

no, just write your code with '\ n' and that’s enough. since getting text from textarea means exporting to a text form that can be presented as a file or something else, and then from https://en.wikipedia.org/wiki/Newline

When writing to a file, a node device, or a / fifo socket in text mode, '\ n' is transparently translated into a sequential new line sequence, the system used, which can be longer than one character. When reading in the text mode, a new sequence of lines of a new line will be translated to "\ n". In binary mode, translation is not performed, and the internal representation created by '\ n' is output directly.

it really depends on what you want to do with it. if you send it back to your server, then it is up to you if you want to export it as a file and then to the OS. but, as a rule, it is almost always safe to use "\ n" since it was more common and generally accepted.

 $(function(){ var $text = $("#text"); $text.val( $text.val() + "Hello \nThis is '\\r' a \r" + // here "multi-line (\\r\\n) \r\n text with" + // here CRLF " differents \n linefeeds" ); var s = $text.val().split('\n'); // notice line 3 on output, it been feed by '\r' // and we split only by '\n' $text.val( s.map( (ss,n) => n + "\t" + ss ).join("\n") ); $("#wonder").on("click",function() { $text.val( $text.val().split("\n").join("\t\\r\r") ); // var s = $text.val(); // either sending it via AJAX or // export it to user, it safe to go with '\n' . }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id="text" rows="7" cols="37"> Hey<br>there\n </textarea> <br> <button id="wonder">wonder</button> 
0
source

Source: https://habr.com/ru/post/1276296/


All Articles