JavaScript 换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4321041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:53:13  来源:igfitidea点击:

JavaScript Newline Character

javascript

提问by Jiew Meng

From this question, this ...

这个问题,这...

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

is one way to split a string, but how do I join it back with newlines?

是拆分字符串的一种方法,但如何用换行符将其连接回来?

Also, I wonder if I is say linux which uses whichever newline character, then switch to windows, won't my web app break? The newlines become not recognized? Or maybe the browser does some conversion?

另外,我想知道我是否说 linux 使用任何换行符,然后切换到 Windows,我的网络应用程序不会中断吗?换行符无法识别?或者浏览器进行了一些转换?

采纳答案by kennebec

Split it on /\r?\n/, in case the string includes the carriage returns with newlines.

将其拆分为 /\r?\n/,以防字符串包含带换行符的回车符。

join it with '\n', in any browser and any os.

在任何浏览器和任何操作系统中用 '\n' 加入它。

回答by David Tang

If you want to join using newline characters, just do:

如果您想使用换行符加入,只需执行以下操作:

lines.join("\r\n");

But if you want to display on the HTML page, you'd want to wrap each line in <p></p>tags:

但是如果你想在 HTML 页面上显示,你需要用<p></p>标签包裹每一行:

html = "<p>" + lines.join("</p><p>") + "</p>";

回答by Jacob Relkin

You can use the Arrayobject's joinmethod to glue together array elements into a string:

您可以使用Array对象的join方法将数组元素粘合到一个字符串中:

lines.join("\r\n");

回答by Eran Medan

As said, join is the best, but here is the hard way (untested, I hope it's not too trivial):

如前所述, join 是最好的,但这是一种艰难的方式(未经测试,我希望它不是太琐碎):

var result;

for (i=0;i<lines.length;i++){
   result+=lines[i]+"\r\n"; //depends on OS
}