50

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?

Community
  • 1
  • 1
Jiew Meng
  • 84,767
  • 185
  • 495
  • 805

6 Answers6

61

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>";
David Tang
  • 92,262
  • 30
  • 167
  • 149
45

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;
Syntle
  • 5,168
  • 3
  • 13
  • 34
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
28

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.

kennebec
  • 102,654
  • 32
  • 106
  • 127
  • 17
    In the node REPL you'll see a literal `\n` in the output for `['foo','bar'].join('\n')`, however if you run `console.log(['foo','bar'].join('\n'))` you'll see the expected result. Hope this helps someone else out there. –  Jul 09 '15 at 19:26
0

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
}
Eran Medan
  • 44,555
  • 61
  • 184
  • 276
0

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

lines.join(`
`)
Marinos An
  • 9,481
  • 6
  • 63
  • 96
0

I used '\r' is OK, macOS 12.6, chrome 109.0.5414.119

lines.join('\r')
DuskL
  • 11
  • 1
  • 1
  • 6