Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Newline Character

Tags:

javascript

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?

like image 237
Jiew Meng Avatar asked Dec 01 '10 03:12

Jiew Meng


People also ask

How do you write a newline character?

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'.

Why does \n not work in JavaScript?

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.

Can you put \n in a string?

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.


1 Answers

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>"; 
like image 184
David Tang Avatar answered Oct 04 '22 07:10

David Tang