Javascript new line
In JavaScript, there are a few ways to represent a new line:
-
Using the
\n
character: You can use the\n
character to represent a new line. For example:var myString = "Hello\nWorld!";
This will output:
Hello World!
-
Using the
<br>
tag: You can use the<br>
tag to represent a new line. For example:var myString = "Hello<br>World!";
This will output:
Hello World!
Note that the
<br>
tag is only valid in HTML contexts, not in plain text. -
Using the
\r\n
characters: On Windows, you can use the\r\n
characters to represent a new line. For example:var myString = "Hello\r\nWorld!";
This will output:
Hello World!
Note that
\r\n
is only necessary on Windows, as other operating systems use different newline characters. -
Using the
String.prototype.split()
method: You can use thesplit()
method to split a string into an array of substrings, using a newline character as the separator. For example:var myString = "Hello\nWorld!"; var lines = myString.split("\n"); console.log(lines); // Output: ["Hello", "World!"]
-
Using the
String.prototype.replace()
method: You can use thereplace()
method to replace newline characters with a new line. For example:var myString = "Hello\nWorld!"; var newLine = myString.replace(/\n/g, "<br>"); console.log(newLine); // Output: "Hello<br>World!"
Note that the
\n
character is replaced with<br>
in this example, which is only valid in HTML contexts.