Add a new line in a JavaScript or a HTML document
This post will discuss how to add a new line in a JavaScript or a HTML document.
A newline is a special character that moves the cursor to the next line. There are several ways to add a newline in JavaScript, depending on where we want to print it. Here are some of the methods we can use:
1. Using \n escape sequence
We can insert a newline character in a string literal by using the \n escape sequence. The \n character is called an escape sequence, which means it has a special meaning and is not printed as a normal character. We can use this when we want to add a newline in the console, in an alert box, or in any other place that accepts a string. Here’s an example of how we can achieve this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Create a string with a newline character let str = "Hello\nWorld"; // Print the string in the console console.log(str); // Hello // World // Print the string in an alert box alert(str); // Hello // World |
As demonstrated, to insert a new line in JavaScript, we need to use the special character \n inside a string. There are other escape sequences in JavaScript, such as \t for a tab, \r for a carriage return, and \" for a double quote.
2. Using <br> HTML tag
However, if we are writing HTML code with JavaScript, the \n character will not create a visible line break in the browser. Instead, we need to use the HTML tag <br> to insert a line break. For example, if we want to write "Hello" and "World" on two separate lines in an HTML document, we can do this:
|
1 2 3 4 |
document.write("Hello<br>World"); // Hello // World |
The <br> tag is an HTML element that tells the browser to start a new line. There are other HTML elements that can create line breaks, such as <p> for paragraphs, <h1> for headings, and <li> for list items. We can directly insert a line break in an HTML document by using the <br> HTML tag. Here’s an example of how we can achieve this:
|
1 2 3 4 5 |
<!-- Create a paragraph with a line break --> <p>Hello<br>World</p> <!-- Create a table cell with a line break --> <td>Hello<br>World</td> |
3. Using CSS property
Finally, we can use the CSS property white-space: pre to preserve the whitespace characters in our text, such as spaces, tabs, and newlines. We can this property on an HTML element to make it display the text as it is written in the source code, without collapsing or ignoring the whitespace characters. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<style> label { white-space: pre; } </style> <label> Hello World! This is my string </label> <!-- Prints: Hello World! This is my string --> |
That’s all about adding a new line in a JavaScript or a HTML document.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)