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?
There are two basic new line characters: LF (character : \n, Unicode : U+000A, ASCII : 10, hex : 0x0a): This is simply the '\n' character which we all know from our early programming days. This character is commonly known as the 'Line Feed' or 'Newline Character'.
8. The reason it is not working is because javascript strings must be terminated before the next newline character (not a \n obviously). The reason \n exists is to allow developers an easy way to put the newline character (ASCII: 10) into their strings. Your code will have a syntax error at that point and cease to run.
In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.
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>";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With