When working with JavaScript, there are times when you need to add a new line to your output. In this blog post, we’ll cover several methods to create a new line in JavaScript.
1. Using the newline character \n
The newline character \n
is used to create a new line in text strings. This is useful when you’re working with console output or plain text files. For example:
console.log("This is line 1.\nThis is line 2.");
This will output:
This is line 1. This is line 2.
Note that the newline character \n
does not work with HTML output. For HTML, we use the <br>
tag as shown in the next method.
2. Using the HTML line break tag <br>
When working with HTML, you can use the <br>
tag to create a new line. Here’s an example:
document.getElementById("demo").innerHTML = "This is line 1.<br>This is line 2.";
This will output:
This is line 1. This is line 2.
Inside an HTML element, the <br>
tag creates a new line.
3. Using template literals (backticks)
In ES6 (ECMAScript 2015), we can use template literals (enclosed by backticks) to create multi-line strings. Here’s an example:
const text = `This is line 1. This is line 2.`; console.log(text);
This will also output:
This is line 1. This is line 2.
Note that using template literals with HTML elements still requires you to use the <br>
tag for a new line.
4. Using the innerText
property
If you’re working with a <pre>
or a <textarea>
element, you can use the innerText
property to preserve newline characters:
const text = "This is line 1.\nThis is line 2."; document.getElementById("demo").innerText = text;
This will output:
This is line 1. This is line 2.
The innerText
property interprets newline characters as a new line, just like in plain text files or console output.
Conclusion
In this blog post, we’ve covered several methods to create a new line in JavaScript. Depending on your use case, you can choose the method that best fits your needs. Remember to use the newline character \n
for console output and plain text files and the <br>
tag when working with HTML elements.