简体   繁体   English

JavaScript字符串换行符?

[英]JavaScript string newline character?

Is \\n the universal newline character sequence in Javascript for all platforms? \\n是否适用于所有平台的Java语言中的通用换行符序列? If not, how do I determine the character for the current environment? 如果不是,我如何确定当前环境的角色?

I'm not asking about the HTML newline element ( <BR/> ). 我不是在问HTML换行符( <BR/> )。 I'm asking about the newline character sequence used within JavaScript strings. 我问的是JavaScript字符串中使用的换行符序列。

I've just tested a few browsers using this silly bit of JavaScript: 我刚刚使用了一些愚蠢的JavaScript测试了一些浏览器:

 function log_newline(msg, test_value) { if (!test_value) { test_value = document.getElementById('test').value; } console.log(msg + ': ' + (test_value.match(/\\r/) ? 'CR' : '') + ' ' + (test_value.match(/\\n/) ? 'LF' : '')); } log_newline('HTML source'); log_newline('JS string', "foo\\nbar"); log_newline('JS template literal', `bar baz`); 
 <textarea id="test" name="test"> </textarea> 

IE8 and Opera 9 on Windows use \\r\\n . Windows上的IE8和Opera 9使用\\r\\n All the other browsers I tested (Safari 4 and Firefox 3.5 on Windows, and Firefox 3.0 on Linux) use \\n . 我测试过的所有其他浏览器(Windows上的Safari 4和Firefox 3.5,Linux上的Firefox 3.0)都使用\\n They can all handle \\n just fine when setting the value, though IE and Opera will convert that back to \\r\\n again internally. 设置值时,它们都可以很好地处理\\n ,尽管IE和Opera会在内部再次将其转换回\\r\\n There's a SitePoint article with some more details called Line endings in Javascript . 有SitePoint文章,其中有更多详细信息,称为Java中的行尾

Note also that this is independent of the actual line endings in the HTML file itself (both \\n and \\r\\n give the same results). 还要注意,这与HTML文件本身中的实际行尾无关( \\n\\r\\n给出相同的结果)。

When submitting a form, all browsers canonicalize newlines to %0D%0A in URL encoding. 提交表单时,所有浏览器都将URL编码中的换行符规范化为%0D%0A To see that, load eg data:text/html,<form><textarea name="foo">foo%0abar</textarea><input type="submit"></form> and press the submit button. 为此,请加载例如data:text/html,<form><textarea name="foo">foo%0abar</textarea><input type="submit"></form>并按提交按钮。 (Some browsers block the load of the submitted page, but you can see the URL-encoded form values in the console.) (某些浏览器阻止了已提交页面的加载,但是您可以在控制台中看到URL编码的表单值。)

I don't think you really need to do much of any determining, though. 不过,我认为您真的不需要做任何决定。 If you just want to split the text on newlines, you could do something like this: 如果只想在换行符上分割文本,则可以执行以下操作:

lines = foo.value.split(/\r\n|\r|\n/g);

Yes, it is universal. 是的,它是通用的。

Although '\\n' is the universal newline characters, you have to keep in mind that, depending on your input, new line characters might be preceded by carriage return characters ( '\\r' ). 尽管'\\n'是通用换行符 ,但是必须记住,根据您的输入,换行符可能以回车符( '\\r''\\r'

Don't use "\\n". 不要使用“ \\ n”。 Just try this: 尝试一下:

var string = "this\
is a multi\
line\
string";

Just enter a back-slash and keep on truckin'! 只需输入反斜杠并继续进行即可! Works like a charm. 奇迹般有效。

It might be easiest to just handle all cases of the new line character instead of checking which case then applying it. 仅处理换行符的所有情况,而不是先检查哪种情况然后应用它,可能是最简单的。 For example, if you need to replace the newline then do the following: 例如,如果您需要替换换行符,请执行以下操作:

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

是的,请使用\\ n,除非要生成要在其中使用<br /> html代码。

Email link function i use "%0D%0A" 电子邮件链接功能我使用“%0D%0A”

function sendMail() {   
var bodydata="Before "+ "%0D%0A";
    bodydata+="After"

var MailMSG = "mailto:aaa@sss.com" 
         + "?cc=07@sss.com" 
         + "&subject=subject" 
         + "&body=" + bodydata; 
window.location.href = MailMSG; 
} 

[HTML] [HTML]

<a href="#" onClick="sendMail()">Contact Us</a>

Get a line separator for the current browser: 获取当前浏览器的行分隔符:

function getLineSeparator() {
  var textarea = document.createElement("textarea");
  textarea.value = "\n"; 
  return textarea.value;
}

A note - when using ExtendScript JavaScript (the Adobe Scripting language used in applications like Photoshop CS3+), the character to use is "\\r". 注意-使用ExtendScript JavaScript(在Photoshop CS3 +等应用程序中使用的Adobe脚本语言)时,使用的字符为“ \\ r”。 "\\n" will be interpreted as a font character, and many fonts will thus have a block character instead. “ \\ n”将被解释为字体字符,因此许多字体将改为具有块字符。

For example (to select a layer named 'Note' and add line feeds after all periods): 例如(要选择一个名为“ Note”的图层并在所有期间后添加换行符):

var layerText = app.activeDocument.artLayers.getByName('Note').textItem.contents;
layerText = layerText.replace(/\. /g,".\r");

You can use `` quotes (wich are below Esc button) with ES6. 您可以在ES6中使用``引号(Esc按钮下方的引号)。 So you can write something like this: 所以你可以这样写:

var text = `fjskdfjslfjsl
skfjslfkjsldfjslfjs
jfsfkjslfsljs`;

I had the problem of expressing newline with \\n or \\r\\n . 我有用\\ n\\ r \\ n表示换行的问题。
Magically the character \\r which is used for carriage return worked for me like a newline. 神奇的是,用于回车的字符\\ r像换行符一样为我工作。
So in some cases, it is useful to consider \\r too. 因此,在某些情况下,考虑\\ r也很有用。

I believe it is -- when you are working with JS strings. 我相信是-当您使用JS字符串时。

If you are generating HTML, though, you will have to use <br /> tags (not \\n , as you're not dealing with JS anymore) 但是,如果要生成HTML,则必须使用<br />标签(而不是\\n ,因为您不再使用JS了)

printAccountSummary: function()
        {return "Welcome!" + "\n" + "Your balance is currently $1000 and your interest rate is 1%."}
};
console.log(savingsAccount.printAccountSummary()); // method

Prints: 印刷品:

Welcome!
Your balance is currently $1000 and your interest rate is 1%.

A practical observation... In my NodeJS script I have the following function: 实际观察...在我的NodeJS脚本中,我具有以下功能:

function writeToLogFile (message) {
    fs.appendFile('myserverlog.txt', Date() + " " + message + "\r\n", function (err) {
        if (err) throw err;
    });
}

First I had only "\\n" but I noticed that when I open the log file in Notepad, it shows all entries on the same line. 首先,我只有“ \\ n”,但是我注意到在记事本中打开日志文件时,它在同一行显示所有条目。 Notepad++ on the other hand shows the entries each on their own line. 另一方面,Notepad ++在各自的行上显示条目。 After changing the code to "\\r\\n", even Notepad shows every entry on its own line. 将代码更改为“ \\ r \\ n”后,即使记事本也会在每行中显示每个条目。

The \\n is just fine for all cases I've encountered. \\n对于我遇到的所有情况都很好。 I you are working with web, use \\n and don't worry about it (unless you have had any newline-related issues). 如果您使用的是网络,请使用\\n ,不必担心(除非您遇到任何与换行有关的问题)。

您可以使用<br/>document.write/document.writeln之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM