Add new line js
Here are a few ways to add a new line in JavaScript:
-
Using the
\n
character:var myString = "Hello\nWorld!";
This will add a new line character (
\n
) to the end of the string. -
Using the
+
operator:var myString = "Hello" + "\n" + "World!";
This will concatenate the strings with a new line character in between.
-
Using the
String.prototype.concat()
method:var myString = "Hello"; myString = myString.concat("\n", "World!");
This will concatenate the strings with a new line character in between.
-
Using the
String.prototype.replace()
method:var myString = "Hello"; myString = myString.replace(/\n/g, "\r\n");
This will replace all occurrences of the new line character (
\n
) with a carriage return and line feed (\r\n
). -
Using the
String.prototype.split()
method:var myString = "Hello\nWorld!"; var lines = myString.split("\n");
This will split the string into an array of lines, using the new line character as the separator.
Note that the \n
character is used to represent a new line in most operating systems, but it may not work as expected in all cases. For example, in Windows, you may need to use \r\n
to represent a new line.