【问题标题】:Getting the platform specific newline character in JavaScript?在 JavaScript 中获取平台特定的换行符?
【发布时间】:2013-01-24 18:32:43
【问题描述】:

几年前,我为我的一个 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 告诉我特定于平台的换行符是什么?也许是某种内置的实用功能?我在我的扩展程序编写的文本文件中使用这些换行符,并且我想使用特定于平台的换行符,以便文件在各种系统中看起来都合适。

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

【问题讨论】:

标签: javascript firefox firefox-addon newline


【解决方案1】:

这是我最终使用的:

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 变量中列为可能性(我正在通过nsIXULRuntime 中的OS 属性进行测试)。

【讨论】:

    【解决方案2】:

    更新 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".
    

    【讨论】:

      【解决方案3】:

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

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

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

      Environment.NewLine
      

      【讨论】:

      • 不幸的是,我没有生成任何 HTML(它是一个简单的纯文本文件),而且我对 client 端的换行符(即操作系统哪个 Firefox 正在运行)。
      猜你喜欢
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      相关资源
      最近更新 更多