Add new line in javascript
In JavaScript, you can add a new line in several ways:
-
Using the
\n
character:var myString = "Hello\nWorld!";
This will add a new line character (
\n
) to the string, which will be rendered as a new line in most browsers and text editors. -
Using the
document.write()
method:document.write("Hello<br>World!");
This will add a new line to the HTML document using the
<br>
tag, which is a common way to add a line break in HTML. -
Using the
innerHTML
property:var myDiv = document.getElementById("myDiv"); myDiv.innerHTML = "Hello<br>World!";
This will add a new line to an HTML element (in this case, a
div
element) using theinnerHTML
property. -
Using the
createElement()
method:var myP = document.createElement("p"); myP.textContent = "Hello"; myP.innerHTML += "<br>World!"; document.body.appendChild(myP);
This will create a new paragraph element (
<p>
) and add a new line to it using theinnerHTML
property. -
Using the
console.log()
method:console.log("Hello\nWorld!");
This will add a new line to the console output, which is useful for debugging purposes.
Note that the \n
character is not a literal newline character, but rather an escape sequence that represents a newline character. In most cases, you can use \n
to add a new line in JavaScript.