开发者

JavaScript Newline Character

开发者 https://www.devze.com 2023-01-28 06:15 出处:网络
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?

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?


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>" + lines.join("</p><p>") + "</p>";


You can use the Array object's join method to glue together array elements into a string:

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

In CSS: remember to use

white-space: pre;


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

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


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

var result;

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


The following seems a future-proof, os-independent code:

lines.join(`
`)
0

精彩评论

暂无评论...
验证码 换一张
取 消