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

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

本文介绍了在JavaScript中获得平台特定的换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 <$ c 

$ c> GetNewLine:function()
{
var platform = navigator.platform.toLowerCase();

if(platform.indexOf('win')!= -1)// Windows
return\r\\\
;
else if(platform.indexOf('mac')!= -1)// Mac
return\r;
else // * nix
返回\\\
;



$ b $ p
$ b这似乎工作正常,但在阅读,我注意到最近的苹果操作系统(OS X和更高版本)现在使用UNIX风格 \\\
结束。因此,我的小函数可能会返回错误的东西(我没有Mac OS来测试它)。



有一种方法可以让Firefox告诉我特定于平台的换行符是什么?也许某种内置的效用函数?我在我的扩展名写入的文本文件中使用这些换行符,并且我想使用特定于平台的文本文件,以便文件在各种系统中看起来是合适的。


$ b

因此,在Mac mini(OS X)上运行 navigator.platform.toLowerCase()函数调用时, ,我得到输出值 macintel 。这将导致我的函数返回 \r ,而不是 \\\
,因为它应该。 b $ b

解决方案

这是我最终使用的:

  GetNewLine:function()
{
var OS = Components.classes [@ mozilla.org/xre/app-info;1]。
getService(Components.interfaces.nsIXULRuntime).OS;

return /winnt|os2/i.test(OS)? \r\\\
:/mac/i.test(OS)? \r:\\\
;





$ b

我很确定mac情况不会发生,它没有列在变量(我正在测试通过 nsIXULRuntime 中的 OS 属性。


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

这篇关于在JavaScript中获得平台特定的换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 11:43