Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What's the proper way of handling line feeds on Windows, Mac and Linux. Let's say I have a simple web app that has a textarea and I need to do a string split every new line. Is it safe to convert \r\n and \r to \n before processing the content of the textarea, or do I need to detect what OS is the user is on and apply conditional statement to each?

Sample Code

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);
like image 208
Vianne Avatar asked Nov 07 '22 08:11

Vianne


1 Answers

no just write your code with '\n' and that's enough. since get the text from textarea means exporting to a text form that can be represent as file or whatever and then so from https://en.wikipedia.org/wiki/Newline

When writing to a file, device node, or socket/fifo in text mode, '\n' is transparently translated to the native newline sequence used by the system, which may be longer than one character. When reading in text mode, the native newline sequence is translated back to '\n'. In binary mode, no translation is performed, and the internal representation produced by '\n' is output directly.

it's very depends on what you want to do with it. if you send it back to your server then it's depends on you if you want to export it to user as a file then it's OS. but generally it's almost always safe to just use '\n' since it's been 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's 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's 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>
like image 101
nullqube Avatar answered Nov 15 '22 05:11

nullqube