在JavaScript中获取特定于平台的换行符

Getting the platform specific newline character in JavaScript?

本文关键字:平台 换行符 于平台 JavaScript 获取      更新时间:2023-09-26

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

这似乎还可以,但在阅读维基百科的新文章时,我注意到最近的苹果操作系统(OS X和更高版本)现在使用UNIX风格的'n行结尾。因此,对于这种情况,我的小函数可能返回了错误的东西(我没有一个Mac操作系统来测试它)。

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

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

以下是我最终使用的内容:

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属性测试)。

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

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

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

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

Environment.NewLine