Years ago, I wrote the following function for one of my Firefox add-ons which helps me obtain a platform specific newline character:
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 OK, but upon reading the newline Wikipedia article, I noted that recent Apple operating systems (OS X and later) now use the UNIX style \n
line ending. As such, my little function may be returning the wrong thing for that case (I don't have a Mac OS on which to test it).
Is there a way I can get Firefox to tell me what the platform-specific newline character is? Perhaps some sort of built-in utility function? I'm using these newlines in the text files my extension writes, and I want to use the platform specific one, so that the files look appropriate across various systems.
Update (2-13-2013): So upon running the navigator.platform.toLowerCase()
function call on a Mac-mini (OS X), I get the output value macintel
. This would result in my function returning \r
instead of \n
as it should.
Here's 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'm pretty sure the "mac" case should never happen, seeing as it's not listed as a possibility in the OS TARGET variable (which I'm testing via the OS
property in nsIXULRuntime
).
UPDATE 1/16/15: encoding does not handle os specific new line character.
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 the TextEncoder it encodes your \n to 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".
No need for any determining if you just want to split the text on newlines, you could do something like this:
htmlstring = sNewLine.replace(/(\r\n|\n|\r)/gm, "<br>");
If you need the underlying webservers newline, you can get it with an Ajax call and return something like this if using ASP.NET
Environment.NewLine