How to add new lines to console and DOM output in JavaScript

When you have a string and want to display it on the screen, you might need to create line breaks in the string to aid with readability.
There are two main ways to display a string in JavaScript and that is through the console or by adding it directly to your HTML.
In this post, we'll learn how to output strings with line breaks in JavaScript.
Adding new lines in your console
The most common scenario is outputting a line with line breaks to the console.
To add a new line in your string, simply use the new line character (\n
) in your string.
The \n
character is used to create a new line in the string, turning the string into a multi-line string.
When you log it to the console, it will automatically create a new line for you.
const string = "Hello\nWorld";
console.log(string);
Hello
World
If you don't want to use \n
to create a new line, you can make use of template literals.
Template literals are strings that can contain new line breaks formed when pressing enter.
const string = `Hello
World`;
console.log(string);
Hello
World
Because template literals also support interpolation, they are the recommended way to add line breaks to a string, especially because they are arguably more readable as well.
Adding new lines in your HTML
If you prefer to see your string as a multi-line string in your HTML, you can use the <br>
tag to create a new line.
One way to easily inject HTML is to write it directly to the document:
const string = "Hello<br>World";
document.body.innerHTML = string;
Hello
World
Another way to do this is by writing to the document
object:
document.write("Hello<br>World");
Hello
World
Conclusion
In this post, we learned how to output strings with line breaks in JavaScript.
Simply use the \n
character to create a new line in your string or use the <br>
tag to create a new line in your HTML.
Thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on X! You can also join the conversation over at our official Discord!
Leave us a message!