多年前,我为我的一个Firefox附加组件编写了以下函数,这有助于我获得特定于平台的换行符:
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";
}
这似乎工作正常,但在阅读newline Wikipedia article后,我注意到最近的Apple操作系统(OS X及更高版本)现在使用UNIX样式\n
行结尾。因此,我的小功能可能会为这种情况返回错误的东西(我没有可以测试它的Mac OS)。
有没有办法让Firefox告诉我特定于平台的换行符是什么?也许某种内置的实用功能?我在我的扩展程序编写的文本文件中使用这些换行符,并且我想使用特定于平台的文件,以便文件在各种系统中看起来合适。
更新(2-13-2013):因此,在Mac-mini(OS X)上运行navigator.platform.toLowerCase()
函数调用时,我得到输出值macintel
。这会导致我的函数返回\r
而不是\n
。
答案 0 :(得分:2)
这是我最终使用的内容:
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";
}
我非常肯定" mac"因为OS TARGET变量(我通过OS
中的nsIXULRuntime
属性进行测试)未将其列为可能性,因此情况永远不会发生。 / p>
答案 1 :(得分:1)
UPDATE 1/16/15:编码不处理特定于操作系统的新行字符。
来自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
<击> 如果你使用OS.File和TextEncoder它编码你的\ n到os适当(我很确定): 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".
击> <击> 撞击>
答案 2 :(得分:0)
无需确定是否只想在换行符上拆分文本,您可以执行以下操作:
htmlstring = sNewLine.replace(/(\r\n|\n|\r)/gm, "<br>");
如果你需要底层的webservers换行符,可以使用Ajax调用来获取它,如果使用ASP.NET则返回类似的内容
Environment.NewLine