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.
JAVASCRIPTconst string = "Hello\nWorld";
console.log(string);
BASHHello
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.
JAVASCRIPTconst string = `Hello
World`;
console.log(string);
BASHHello
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:
JAVASCRIPTconst string = "Hello<br>World";
document.body.innerHTML = string;
BASHHello
World
Another way to do this is by writing to the document
object:
JAVASCRIPTdocument.write("Hello<br>World");
BASHHello
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!
- Getting Started with TypeScript
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor
- Using Axios to Pull Data from a REST API