Getting a specific newline character in JavaScript?

A few years ago, I wrote the following function for one of my Firefox add-ons, which helps me get the character of a new line of a new line:

GetNewLine: function() { var platform = navigator.platform.toLowerCase(); if(platform.indexOf('win') != -1) // Windows return "\r\n"; else if(platform.indexOf('mac') != -1) // Mac return "\r"; else // *nix return "\n"; } 

This seems to work fine, but after reading through the article on the new Wikipedia article, I noted that the latest Apple operating systems (OS X and above) now use the UNIX-style end of line \n . Thus, my little function may return the wrong thing for this case (I do not have Mac OS to test it).

Is there a way to get Firefox to tell me what a newline character is? Perhaps some kind of built-in utility function? I use these new lines in text files that my extension writes, and I want to use a specific platform so that the files look appropriate on different systems.

Update (2-13-2013): Thus, when I start the call to the navigator.platform.toLowerCase() function on Mac-mini (OS X), I get the output value of macintel . This will cause my function to return \r instead of \n , as it should.

+6
javascript firefox newline firefox-addon
source share
3 answers

Here is what I ended up using:

 GetNewLine: function() { var OS = Components.classes["@mozilla.org/xre/app-info;1"]. getService(Components.interfaces.nsIXULRuntime).OS; return /winnt|os2/i.test(OS) ? "\r\n" : /mac/i.test(OS) ? "\r" : "\n"; } 

I am sure that the “mac” case should never occur, since it is not listed as an option in the OS TARGET variable (which I am testing with the OS property in nsIXULRuntime ).

+2
source share

UPDATE 1/16/15: the encoding does not handle the new character of the string.

from irc:

 07:49 futpib i guess encoding is for charset only 07:49 Will character encoding is nothing to do with OS-specific line-endings 

If you use OS.File and TextEncoder, it encodes your \ n in os appropriate (im pretty sure): https://developer.mozilla.org/en-US/docs/JavaScript_OS.File/OS.File_for_the_main_thread

 let encoder = new TextEncoder(); // This encoder can be reused for several writes let array = encoder.encode("This is some text"); // Convert the text to an array let promise = OS.File.writeAtomic("file.txt", array, // Write the array atomically to "file.txt", using as temporary {tmpPath: "file.txt.tmp"}); // buffer "file.txt.tmp". 

Strike>

+1
source share

There is no need for any definition, if you just want to split the text into newlines, you can do something like this:

 htmlstring = sNewLine.replace(/(\r\n|\n|\r)/gm, "<br>"); 

If you need the basic version of webservers newline, you can get it with an Ajax call and return something like this if using ASP.NET

 Environment.NewLine 
0
source share

All Articles