How to add new line in javascript
In JavaScript, you can add a new line in several ways:
-
Using the
\n
character: You can use the\n
character to create a new line. For example:console.log("Hello\nWorld");
This will output:
Hello World
-
Using the
<br>
tag: You can use the<br>
tag to create a new line. For example:document.write("Hello<br>World");
This will output:
Hello World
Note that the
<br>
tag is only valid in HTML contexts, not in plain JavaScript. -
Using the
document.createElement
method: You can create a new line by creating a<br>
element using thedocument.createElement
method. For example:var br = document.createElement("br"); document.body.appendChild(br);
This will create a new line in the HTML document.
-
Using the
String.prototype.split
method: You can split a string into multiple lines using thesplit
method. For example:var str = "Hello World"; var lines = str.split("\n"); console.log(lines); // Output: ["Hello", "World"]
This will split the string into an array of lines.
-
Using the
String.prototype.replace
method: You can use thereplace
method to add a new line to a string. For example:var str = "Hello World"; str = str.replace(/ /g, "\n"); console.log(str); // Output: "Hello\nWorld"
This will replace all spaces in the string with new lines.
Note that the above methods may not work as expected in all browsers or environments. It's always a good idea to test your code thoroughly to ensure it works as expected.