6

多年前,我为我的一个 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";
}

这似乎工作正常,但在阅读新行 Wikipedia 文章后,我注意到最近的 Apple 操作系统(OS X 和更高版本)现在使用 UNIX 样式的\n行尾。因此,我的小函数可能会针对这种情况返回错误的东西(我没有可以测试它的 Mac OS)。

有没有办法让 Firefox 告诉我特定于平台的换行符是什么?也许某种内置的实用功能?我在我的扩展程序编写的文本文件中使用这些换行符,并且我想使用特定于平台的换行符,以便文件看起来适合各种系统。

更新(2013 年 2 月 13 日):因此,在navigator.platform.toLowerCase()Mac-mini(OS X)上运行函数调用时,我得到了输出值macintel。这将导致我的函数返回\r而不是\n应有的返回。

4

3 回答 3

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)。

于 2014-03-26T14:30:52.610 回答
1

更新 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 编码为适当的操作系统(我很确定): 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".

于 2014-03-26T15:40:28.873 回答
0

无需确定是否只想在换行符上拆分文本,您可以执行以下操作:

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

如果您需要底层网络服务器换行符,您可以通过 Ajax 调用获取它,如果使用 ASP.NET,则返回类似这样的内容

Environment.NewLine
于 2013-02-17T22:15:05.810 回答